The Wayback Machine - https://web.archive.org/web/20231123145531/https://www.geeksforgeeks.org/how-to-play-video-on-mouse-hover-and-pause-on-mouseout-using-javascript/
Open In App
Related Articles

How to Play Video on Mouse Hover and Pause on Mouseout using JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we learn how to play a video when the mouse hovers on it and how to stop it when the mouse is removed from the video element. Sometimes there is a need where we want that video on websites to automatically starts playing when the user keeps the mouse over it because it reduces the number of clicks by the user on the website and gives a great experience to the user. So to achieve that purpose we use javascript to make it playable when the mouse hovers over it and when the mouse comes out then it automatically stops playing.

Approach: First, we will attach a video file to our HTML DOM and then apply mouseover and mouseout event listener on it using javascript. Below is the complete code implementation:

Example: In this example, we will use pure javascript to play the video.

 

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
  
    <!-- Video element -->
    <video src=
        type="video/mp4" muted class="vid" 
        loop style="border: solid; width: 800px;">
    </video>
  
    <script>
  
        // Targeting video element 
        let clip = document.querySelector(".vid")
  
        /* Applying mouseover event on video clip 
        and then we call play() function to play 
        the video when the mouse is over the video */
        clip.addEventListener("mouseover", function (e) {
            clip.play();
        })
  
        /* Applying mouseout event on video clip 
        and then we call pause() function to stop 
        the video when the mouse is out the video */
        clip.addEventListener("mouseout", function (e) {
            clip.pause();
        })
    </script>
</body>
  
</html>


Output:

browser output


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials