Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Mouseevent On Hover

Currently I am looking for some help with my mouse over event.

<div class="video-container">
<video id="my_video" loop muted poster="IMAGE_URL"> <!-- put your image here -->
  <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>

Above is my video-container, on my index page I am displaying 10 videos. Each of them should show a preview of the video when being hovered, however with my current javascript only the first video with my_video id is displaying the video preview when hovering.

let myVideo = document.getElementById("my_video");
myVideo.addEventListener("mouseover", () => {
    myVideo.play()
    image.style.display = 'none'
});

myVideo.addEventListener("mouseleave", () => {
    myVideo.pause();
});

How can I make it so that all videos on my homepage, behave in the same manner?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you do the getElementById, it only covers one element. And ID must be unique to elements in HTML, you cannot have multiple elements with same ID. You can give all of the video elements the same class and apply all of them at once, or just apply to all video elements directly

let myVideos = document.querySelectorAll("video");
myVideos.forEach(vid => {
  vid.addEventListener("mouseover", () => {
    vid.play();
  });
  vid.addEventListener("mouseleave", () => {
    vid.pause();
  });
})
<div id="container">
  <video id="my_video_1" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here -->
  <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
<video id="my_video_2" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here -->
  <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading