Reputation: 305
I'm trying at the moment to target multiple instances of the same div
class (.overlay
) - the basic idea I'm trying to execute is that each div contains a HTML5 video inside another wrapped div which on mouseenter
reveals itself, sets the video timeline to 0 and plays, and on mouseout
resets the video to 0 again.
The problem I'm having is that only the first item of my grid works at the moment with nothing happening on the rollover of the others. This is my Javascript:
$(document).ready(function() {
$('.overlay').mouseenter(function(){
$('#testvideo').get(0).play();
}).mouseout(function() {
$('#testvideo').get(0).pause();
$('#testvideo').get(0).currentTime = 0;
})
});
I've also tried the following
$(document).ready(function() {
$('.overlay').mouseenter.each(function(){
$('#testvideo').get(0).play();
}).mouseout(function() {
$('#testvideo').get(0).pause();
$('#testvideo').get(0).currentTime = 0;
})
});
but that simply broke the functionality all together!
Here is a fiddle showing what should happen: http://jsfiddle.net/jameshenry/ejmfydfy/
The only difference between this and the actual site is that there are multiple grid items and thumbnails. I also don't want the behaviour to by asynchronous but rather individual - does anyone have any idea where I'm going wrong (I'm guessing my javascript!)
Upvotes: 0
Views: 187
Reputation: 11725
The problem is that you're using always $('#testvideo')
, independent on the div
you're entering the mouse. Since the HTML's id
property must be unique, only the first element that you set the id testvideo
will work the way you expect.
You should be using the video
tag referenced by the div.overlay
, or you could add a CSS class to the video
tags, so you could use that class to find the video.
The code below will get the overlayed video, independent of which it is.
$(document).ready(function() {
$('.overlay').hover(function() {
$(this).parent().find('video').get(0).play();
}, function() {
var video = $(this).parent().find('video').get(0);
video.pause();
video.currentTime = 0;
});
});
Take a look at your updated fiddle.
Upvotes: 3
Reputation: 5734
The first way you did it should work, the second one not. But, you shouldn't use an id like #testvideo
if there are a lot of videos (one on each .overley
element). Having multiple instances of the same id produce unexpected behaviuor, like "only working on the first item".
You should change your #testvideo
with .testvideo
and change your code to something like this:
$(document).ready(function() {
$('.overlay').mouseenter(function(){
$(this).find('.testvideo').play();
}).mouseout(function() {
$(this).find('.testvideo').pause();
$(this).find('.testvideo').currentTime = 0;
})
});
Upvotes: 0