Oliver Chalmers Oliver Chalmers - 2 months ago 21
Javascript Question

Video play on hover

I have a selection of video thumbnails that I want to trigger to play/pause on hover. I have managed to get one of them to work, but I run into a problem with the others on the list. Attached is the fiddle of my code. There will be a div covering each html5 video so the hover needs to delegate to the video, which i'm unsure as to how to do.

http://jsfiddle.net/meh1aL74/

Preview of the html here -

<div class="video">
<div class="videoListCopy">
<a href="videodetail.html" class="buttonMore">
<div class="breaker"><div class="line"></div></div>
<div class="buttonContent">
<div class="linkArrowContainer">
<div class="iconArrowRight"></div>
<div class="iconArrowRightTwo"></div>
</div>
<span>Others</span>
</div>
</a>
</div>
<div class="videoSlate">
<video class="thevideo" loop>
<source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</div>
</div>


<div class="video">
<div class="videoListCopy">
<a href="videodetail.html" class="buttonMore">
<div class="breaker"><div class="line"></div></div>
<div class="buttonContent">
<div class="linkArrowContainer">
<div class="iconArrowRight"></div>
<div class="iconArrowRightTwo"></div>
</div>
<span>Others</span>
</div>
</a>
</div>
<div class="videoSlate">
<video class="thevideo" loop>
<source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</div>
</div>


Preview of the javascript here -

var figure = $(".video");
var vid = $("video");

[].forEach.call(figure, function (item) {
item.addEventListener('mouseover', hoverVideo, false);
item.addEventListener('mouseout', hideVideo, false);
});

function hoverVideo(e) {
$('.thevideo')[0].play();
}

function hideVideo(e) {
$('.thevideo')[0].pause();
}


Thank you very much for your help.

Oliver

Answer

Why are you uisng native event binding together with jQuery ?

Anyway, if you want to handle the events natively you can use the .bind method and pass the index of each video to the handlers

var figure = $(".video");
var vid = figure.find("video");

[].forEach.call(figure, function (item,index) {
    item.addEventListener('mouseover', hoverVideo.bind(item,index), false);
    item.addEventListener('mouseout', hideVideo.bind(item,index), false);
});

function hoverVideo(index, e) {
    vid[index].play(); 
}

function hideVideo(index, e) {
    vid[index].pause(); 
}

Demo at http://jsfiddle.net/gaby/0o8tt2z8/2/


Or you can go full jQuery

var figure = $(".video").hover( hoverVideo, hideVideo );

function hoverVideo(e) { $('video', this).get(0).play(); }
function hideVideo(e) { $('video', this).get(0).pause(); }

Demo at http://jsfiddle.net/gaby/0o8tt2z8/1/

Comments