1

I am looking for a way to be able to rig a shortcut to a youtube controll button. I want to be able to click on the left and right arrow to activate "Previous video" and "Next video" on a playlist. I used to be easily able to do it myself, but they made some changes and since those I can't quite replicate what i used to have working.

I use the Google Chrome Shortkey Plug-in to manage my short cut keys. I make the right key execute a javascript code only on "https://www.youtube.com*"

The problem reside in the script to execute. I used to simply do a document.getElementById but now they use class instead of id and I cant get it to work. Their buttons are divs and they go like this:

<div class="ytp-button ytp-button-prev" role="button" aria-label="Previous" tabindex="6050" style="display: inline-block;">
</div>
<div class="ytp-button ytp-button-next" role="button" aria-label="Next" tabindex="6051" style="display: inline-block;">

My code actualy comes from another Stackoverflow Question

Still, if I put all of that together to make the folowing code it doesn't work.

simulate(document.getElementsByClassName("ytp-button ytp-button-prev"), "click");
Community
  • 1
  • 1
Samuel Charpentier
  • 599
  • 1
  • 7
  • 28

4 Answers4

1

getElementsByClassName returns an array, since you can have multiple elements with the same class name. You can pick them by document.getElementsByClassName("ytp-button ytp-button-prev")[index]

jesterjunk
  • 2,342
  • 22
  • 18
jtmarmon
  • 5,727
  • 7
  • 28
  • 45
  • It gives my an index is not defined, should i put a 0 instead? – Samuel Charpentier Jan 04 '15 at 23:07
  • 1
    [*getElementsByClassName*](http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyname) returns a live [*HTMLCollection*](http://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0), which is very different to an Array. ;-) – RobG Jan 04 '15 at 23:14
1

If you are using jQuery, you can target the element then trigger a click event like this:

$( ".ytp-button-prev" ).trigger( "click" );
Liam Schauerman
  • 851
  • 5
  • 10
  • 4
    Answers should explain why they fix the OPs issue. Pushing a particular library that is neither tagged or in the question is not good form. If you are going to do that, you should at least note which one. The *$* variable name is used by a few. – RobG Jan 04 '15 at 23:24
1

jQuery is not the best solution for all our projects, but for simulate events it's not bad option

(function($){
    $('.element').click();
    // same for others ex: $('.element').keyup();
})(jQuery);

example: http://jsfiddle.net/h0po3q3w/

CKGrafico
  • 145
  • 7
0

Jason has your answer, but an alternative is to use document.querySelector. If there is only one button with those classes, or you want the first one, then:

var button = document.querySelector('.ytp-button.ytp-button-prev');
RobG
  • 142,382
  • 31
  • 172
  • 209