Open In App

How to play video on hover on a div using jQuery?

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 allow the video to play on the 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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Play Video on Hover</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <style>
        #video-wrapper {
            display: inline-block;
            position: relative;
        }

        #video {
            display: block;
        }
    </style>
</head>

<body>
    <div id="video-wrapper">
        <video id="video" width="320" 
               height="240" controls muted>
            <source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200107020629/sample_video.mp4"
                type="video/mp4">
            Your browser does not support the video tag.
        </video>
    </div>

    <script>
        $(document).ready(function () {
            let $video = $("#video");

            $("#video-wrapper").on('mouseenter', function () {
                $video.get(0).play();
            });

            $("#video-wrapper").on('mouseleave', function () {
                $video.get(0).pause();
            });
        });
    </script>
</body>

</html>

Output:



Next Article

Similar Reads