I have multiple videos and want to get an event from all of them. But I get only the event from one of them (tested in Chrome). Why?
HTML:
<video id="video1" preload="auto" src="video1.ogg"></video>
<video id="video2" preload="auto" src="video2.ogg"></video>
JS:
$('video').on('canplay', function(){
console.log($(this).attr('id'));
});
EDIT:
Ok.. it is really strange. On the very first load I get sometimes both events. But after that on every reload I get just an event from one of them!? Here a screenshot of my console:
The problem is that the 'canplay' event has already fired by the time you register it. I believe this is because jsFiddle wraps your code inside of $(window).load(...
. If you were to move the script into the html, like on this example , it should work.
Most of the time, if you know for sure that your script is going to run synchronously right after the video element is created with a src
, you can assume that none of those events have been fired. But, just to be safe, and especially when you don't know how your code will be used, I recommend something like this:
function handleCanplay(video) {
console.log($(video).attr('id'));
};
$('video').each(function () {
//first, check if we missed the 'canplay' event
if (this.readyState >= this.HAVE_FUTURE_DATA) {
//yup, we missed it, so run this immediately.
handleCanplay(this);
} else {
//no, we didn't miss it, so listen for it
$(this).on('canplay', function () {
handleCanplay(this);
});
}
});
Working example here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.