Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch video HTML5 play/stop event

How can I listen to the events play/stop/pause of a HTML5 video? I tried with the following code:

$("video").on('play',function(){
    //my code here
});

but it does not work.

Alternatively I would be fine also intercept the click that stop and start the video (in fact I would prefer), but even this code not works:

$('video').on('click', function(event) {
    //my code here
});

I think because often above the video element is placed a div with associated events start and stop, but I do not know how to select via jQuery or Javascript:

P.S. This code should work on pages that are composed dynamically / not generated by me, so I can not refer the elements indicating their ID or a specific class.

UPDATE

I did not realize that the page on which I was testing had a video inside an iframe. The syntax is best suited to my needs:

doc.querySelector("video").addEventListener('play', function(e) {
    //my code here
}, true);
like image 220
jenjis Avatar asked Jan 10 '13 23:01

jenjis


2 Answers

See here:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

So... :

$("video")[0].onplay = function () {
    // Do play stuff here
};

Hope that helps!

like image 56
phonicx Avatar answered Sep 29 '22 14:09

phonicx


Your first attempt should work. But you need to make sure that jQuery is actually finding video elements. You say that the page is generated dynamically, so perhaps it's possible that your code is running before the video elements are added. This would also be the case if your script is higher up in the document than the video elements (e.g., in the <head>).

Try placing the following code immediately before the code you have there and check the output:

console.log($("video"));

If the output is an empty array, then you aren't finding any video elements. Try placing your script at the very end of the page or inside a DOMContentLoaded event. Or, if another script is generating the video elements, make sure your script runs after that one.

A few other notes on your question:

There is no stop event. Here's a list of media events.

I don't think the click event is what you want. That will fire no matter where on the video the user clicks: play button, volume control, etc.

The video being placed inside a div shouldn't have any effect on these events. I'm not sure why you'd have start and end events on a div, so maybe I'm not following.

like image 43
brianchirls Avatar answered Sep 29 '22 15:09

brianchirls