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?
>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>