Reputation: 21
Just trying to get a video to play when another "overlay" div is hovered. Some background on the issue, I have several videos on the page and when hovered, they play.
All works fine until I've added a div that lays above the video. Once I've added a second "overlay" div on top of the video, the code below no longer works because I'm not technically hovered on the video anymore.
I'm using the overlay div on top of the video to put some information about it.
<script type="text/javascript">
var figure = $('.movies');
var vid = $("video");
var cover = $(".video-overlay");
[].forEach.call(vid, function (item) {
item.addEventListener('mouseover', hoverVideo, false);
item.addEventListener('mouseout', hideVideo, false);
});
function hoverVideo(e) {
this.play();
}
function hideVideo(e) {
this.pause();
}
</script>
How can I adjust this to say "If hovered on div class .video-overlay, start the video. If not hovered, pause."
Upvotes: 2
Views: 1402
Reputation: 4869
Solution in javascript:
var vid = document.getElementById("myVideo");
function playVid() {
vid.play();
}
function pauseVid() {
vid.pause();
}
Then, in jQuery I would just do this:
$('.myHoveredElement').hover(function(){
// This will happen when the .myHoveredElement is hovered
vid.play();
}, function(){
// This will happen when the .myHoveredElement is not hovered anymore (mouseleave)
vid.pause();
});
Here is the documentation of the jQuery hover element
If you want it to work on every video that has an element hover it, you will have to give a class to every video's container with an overlay that you want to react on hover. For example, your html will look something like this:
<div class="video-container">
<video ...>
</video>
<div class="video-overlay"></div>
</div>
Then, you'd do something like this:
$('.video-container').hover(function(){
//Happens when you're hover (mouseenter)
$(this).children('video').get(0).play();
}, function(){
// Happens when mouse leaves the video container
$(this).children('video').get(0).stop();
})
This way, it will work when you hover any video that has a container named .video-container on hover.
Hope it answers your questions
Upvotes: 1