Võ Minh
Võ Minh

Reputation: 155

Detect if any video is playing in a webpage using Jquery or/and javascript?

My purpose is detected if one of the two videos are playing and console.log it. I try to build dynamic videos play detect. I read video ID when the user clicks on the play button, and then use the video ID to assign it video for addEventListner but it just works with my first video. the second video doesn't work and

$(function(){

     var videoid = "";

    $('video').bind('play', function (e) {
        videoid = $(this).attr('id');
    });

   $('video').on("click", function() {
   // test if global variable work
            console.log(videoid);
   });

  var abc = 'video1';

  document.getElementById(videoid).addEventListener('playing', function(){
    console.log('play' + videoid);
  })
  document.getElementById(videoid).addEventListener('pause', function(){
    console.log('3443');
  })

  document.getElementById(videoid).addEventListener('ended', function(){
    console.log('242434');
  })

});

what did I wrong?

http://jsfiddle.net/fbc7nn0o/51/

Upvotes: 0

Views: 3105

Answers (2)

Võ Minh
Võ Minh

Reputation: 155

It work for me.

$('video').bind('play', function (e) {

    var videoid = $(this).attr('id');

    document.getElementById(videoid).addEventListener('playing', function(){
        console.log('play' + videoid);
    });
    document.getElementById(videoid).addEventListener('pause', function(){
        console.log('3443');
    });

    document.getElementById(videoid).addEventListener('ended', function(){
        console.log('ended');
    });

});

Upvotes: 0

Kaiido
Kaiido

Reputation: 136628

The video variable in the global scope has not been defined, and thus will fall on document.getElementById(variableName) || document.getElementsByName(variable) || undefined (cf Do DOM tree elements with ids become global variables?).

So addEventListener will only be called from the first <video> element, which as the id "video"...

What you want is

$('video').on({
  play : onplay,
  playing: onplaying,
  pause: onpause
  ...
})

where onplay, onplaying, onpause ... are event handlers functions. e.g function onplaying(e){ $('.text').fadeOut(); console.log('dfdgd'); }.

Also note that $('#'+$(this).attr('id'))[0] is perfect non-sense. Just use this.

Upvotes: 4

Related Questions