How to play video on hover using JavaScript?

In this tutorial, we will be discussing how to play a video on hover using JavaScript.

We will be playing and pausing the video whenever the mouse hovers on the video and pausing the video when the mouse is taken out.

To achieve this, we need to record the events and play/pause the video, here comes JavaScript part.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to use JavaScript to play video on hover</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: red;">Welcome to CodeSpeedy</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: 600px;">
   </video>
   <script>

      let clipVideo = document.querySelector(".vid")

      clipVideo.addEventListener("mouseover", function (e) {
         clipVideo.play();
      })

      clipVideo.addEventListener("mouseout", function (e) {
         clipVideo.pause();
      })
   </script>
</body>
</html>

 

Also read: 3D Photo/Image Gallery (on space) Using HTML5 CSS JS

Leave a Reply

Your email address will not be published. Required fields are marked *