Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Play video when hover on parent div

Tags:

jquery

video

I'm creating a video gallery consisting of thumbnails that play a short video on hover. I've been able to get them to play while hovering over the video itself, but I need them to play when hovering on the video's parent div. Here's my attempt so far:

HTML:

<div class="thumbail">
<video preload="auto" loop>
    <source src="videos/movie.webm" type="video/webm">
    <source src="videos/movie.mp4" type="video/mp4">
    <source src="videos/movie.ogv" type="video/ogg">
</video>
</div>

JavaScript:

$(document).ready(function(){
$(".thumbnail").hover(
function() {
    $(this).children("video").play();
}, function() {
    $(this).children("video").pause();
    $(this).children("video").currentTime = 0;
});
});

Can't figure out what it is I'm doing wrong. Any help would be greatly appreciated. :)

like image 955
Shelby Avatar asked Mar 19 '23 19:03

Shelby


2 Answers

The method pay and pause belongs to the dom element(video object), not the jquery object so

$(document).ready(function () {
    $(".thumbnail").hover(function () {
        $(this).children("video")[0].play();
    }, function () {
        var el = $(this).children("video")[0];
        el.pause();
        el.currentTime = 0;
    });
});

$(this).children("video") returns a jQuery object which does not have the pay/pause methods so your code should through an error(unless you have included some plugins which adds those methods).

You can access the underlying dom element by using the index of the child like $(this).children("video")[0] then call those methods on that element.

like image 151
Arun P Johny Avatar answered Mar 29 '23 08:03

Arun P Johny


play is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element.

$(document).ready(function(){
  $(".thumbnail").hover(
    function() {
      $(this).children("video").get(0).play();
    }, function() {
       $(this).children("video").get(0).pause();
        $(this).children("video").get(0).currentTime = 0;
    });
});

Note: get use for getting the native DOM element from the jQuery selection.

like image 22
Ishan Jain Avatar answered Mar 29 '23 08:03

Ishan Jain