0

I have the following function that I would like to work with a class "pause" instead of an id. I did see a few topics about this however I didn't quite understand how would this work. Thanks!!!

       function onPlayerReady(event) {
            document.getElementById('pause').onclick = function() {
                youtubePlayer1.pauseVideo();
                youtubePlayer2.pauseVideo();
                youtubePlayer3.pauseVideo();
                e.preventDefault();
            };
        };
Antonio Almeida
  • 373
  • 3
  • 13
  • 1
    Duplicate of a lot of posts like [this](http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return) – dramzy Jul 30 '15 at 23:05
  • `document.getElementsByClassName()` returns an array, so if your element is the only one with that class name, you'd get the element at the zeroth index and do whatever you're doing. In JQuery, it's a lot easier: `$( "#classname" ).click(function() { /*your code here*/ });` – dramzy Jul 30 '15 at 23:07

2 Answers2

0

Using jQuery you can attach a click handler to all elements that have the pause class.

    $(".pause").on("click", function () {
            youtubePlayer1.pauseVideo();
            youtubePlayer2.pauseVideo();
            youtubePlayer3.pauseVideo();
            e.preventDefault();
    });
enifeder
  • 487
  • 1
  • 6
  • 16
0

As you can guess from the name, the getElementsByClassName() function can return multiple (or zero) results. This is because element ids must be unique, but many different elements can have the same class.

So all you need to do is iterate over the results and add the click handler as before:

function onPlayerReady(event) {
    var elem = document.getElementById('pause')
    for(var i in elem) {
        elem[i].onclick = function() {
            youtubePlayer1.pauseVideo();
            youtubePlayer2.pauseVideo();
            youtubePlayer3.pauseVideo();
            e.preventDefault();
        }
    }
};

Even though you only expect a single result, this is how you should do it to prevent errors.

Anonymous
  • 11,740
  • 3
  • 40
  • 50