How to Play Video on Mouse Hover and Pause on Mouseout using JavaScript ?
Last Updated :
22 Nov, 2021
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 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
Share your thoughts in the comments
Please Login to comment...