Skip to content
Related Articles

Related Articles

How to play video on hover on a div using jQuery ?
  • Last Updated : 01 Dec, 2020

Given a video on the website and the task is to play it while hovering the cursor on the video and stop the video play on removing the cursor from the video div using jQuery events.

Example: Suppose you are in a hurry and you don’t have time to view the whole video of the article, then you can just hover over the video to see its content without opening the whole video. This method is very efficient and can be used to save data and time of the user. This approach is most commonly used on YouTube and other popular video streaming websites that allows the video to play on hover of the cursor.

Approach: One can play the video on hover using the jQuery. For this, they need to have mouseenter function that will allow the video to play on hovering the mouse cursor over the video. Similarly, one can pause the video by playing the mouseleave function of the jQuery. 

Using jQuery mouseenter() Method: The mouseenter() method is an inbuilt method in jQuery which works when mouse pointer moves over the selected element.

Using jQuery mouseleave() Method: The mouseleave() method is an inbuilt method in jQuery which works when the mouse pointer leaves the selected element.



Code Implementation:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <meta name="viewport" content=
        "width=device-width", initial-scale=1>
        integrity=
"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous">
    </script>
  
    <script src="jquery.hoverplay.js"></script>
</head>
  
<body>
    <div id="video-wrapper">
        <video id="video" width="320" height="240" 
            controls data-play="hover" muted="muted">
            <source src=
                type="video/mp4">
            Your browser does not 
            support the video tag.
        </video>
    </div>
  
    <script>
  
        // Getting video element using jQuery
        var video = $("#video");
  
        // Check if video is ready to play
        $(video).on('canplay', function () {
            $(video).mouseenter(function () {
                $(this).get(0).play();
            }).mouseleave(function () {
                $(this).get(0).pause();
            })
        });
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :