How to use JavaScript to play a video on Mouse Hover and pause on Mouseout?

JavascriptWeb DevelopmentFront End Technology

In this article, we will be exploring the event listeners and how to use them for pausing and playing a video. We will be using the mouse over and the mouseout events to control the video.

The main element of this article includes playing the video whenever the mouse hovers over the video and stopping/pausing the video when the mouse is taken out of that div.

For achieving this specific purpose, we will be using JavaScript that will record the events and play/pause the video.

Approach

We will attach a video to our HTML DOM element and then apply the mouse over and mouse out event listener. Whenever the DOM listens to this event it will trigger the JavaScript function that will tell the template to start or stop the video.

Example

In the below example, we are using the mouse event listeners to play and pause the video when required.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Playing/Pausing Video</title>
   <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>
   <h1 style="color: green;">Welcome to Tutorials Point</h1>
   <!-- Video element -->
   <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
type="video/mp4" muted class="vid" loop style="border: solid; width: 550px;">
   </video>
   <script>

      // Listening to the video element
      let clip = document.querySelector(".vid")

      /* Adding the event listeners on the video to play/pause the video. */
      clip.addEventListener("mouseover", function (e) {
         clip.play();
      })

      /* Applying the mouse out event to pause the video */
      clip.addEventListener("mouseout", function (e) {
         clip.pause();
      })
   </script>
</body>
</html>

Output

raja
Updated on 27-Apr-2022 09:53:24

Advertisements