Reputation: 592
Searched a lot on SO and google but nothing I have tried so far is working as intended. I am trying to catch video events with JQuery.
This is a slightly different case as I am tweaking an already existing divs html content from a regular image to a video.
I have the following div in html:
<div id="video" class="grid_cell"><img src="../assets/test.jpg" /></div>
And with JavaScript and JQuery I do the following to the div:
vidDiv.html('<video width="' + w + '" height="' + h + '" autoplay="autoplay">' +
'<source src="' + src + '" type="video/mp4"></source>' +
'</video>');
This works and replaces the image content with video content instead. However when I am trying to listen to the video's events I get nothing. See the following code I use for this:
vidDiv.bind('mouseleave ended', function(){
console.log("Event triggered!");
});
Note I have tried on
instead of bind
to not success. And the element vidDiv is a JQuery object I fetch earlier. As the vidDiv.html(...)
part works and changes the content to a video I know the connection is correct.
Also I put in the mouseleave
event intentionally to see if any event would trigger and sure enough when leaving the div with the mouse it works. But when the video is finished playing I get no such event.
Any ideas?
EDIT:
I accepted the answer below which works but I also wanted to just put in here an alternative way to do it with pure JS and some JQuery:
vidDiv.html('<video width="' + w + '" height="' + h + '" autoplay="autoplay">' +
'<source src="' + src + '" type="' + type + '"></source>' +
'</video>');
var elementId = vidDiv.attr("id");
var elem = document.getElementById(elementId);
elem.addEventListener('ended', function(e) { console.log("Video ended"); }, true);
Upvotes: 2
Views: 1119
Reputation: 318182
Create proper elements with event handlers:
var fn = function() {
console.log('Event triggered!')
},
video = $('<video />', {
width : w,
height : h,
autoplay : 'autoplay',
on : {
mouseleave: fn,
ended : fn
}
}),
source = $('<source />', {
src : src,
type : 'video/mp4'
}
);
vidDiv.html( video.append(source) );
Upvotes: 1