-2

I am using Javascript to play an HTML5 video when you hover over it, and then pause the video once the mouse exits. The module is working correctly in that sense, except it only works for the first video on the page. There are seven videos total, all using the same div structure.

You can see this in action here: https://dcd.gdr.mybluehost.me/website_33a4bb40/

Following is the JS file that I am using:

jQuery(document).ready(function($){
const video = document.querySelector(".video-container video");

    video.addEventListener("mouseenter", () => {
      video.play();
    });
    
        video.addEventListener("mouseleave", () => {
          video.pause();
    });
}); 

And following is the HTML that contains the video:

<div class="video-container">
    <video
          src="https://dcd.gdr.mybluehost.me/website_33a4bb40/wp-content/uploads/2025/10/cael-dadian-portfolio-iphone-beat-packs-1.mp4"
          muted="muted"
          poster="https://dcd.gdr.mybluehost.me/website_33a4bb40/wp-content/uploads/2025/10/cael-dadian-portfolio-thumbnail-iphone-beat-packs-1.jpg">
     </video>
</div>

I am not seeing any console errors in the inspector. Thank you

2
  • 1
    querySelector returns one single element (or null, if not found.) You need to use querySelectorAll instead, and then iterate over the resulting NodeList. Commented Oct 16 at 6:35
  • Thank you so much for the reply. I am not familar with NodeLists unfortunately. I have updated line 2 to be: const video = document.querySelectorAll(".video-container video"); But now I am getting the console error: video.addEventListener is not a function Thoughts? Commented Oct 17 at 15:01

1 Answer 1

1

Iterate over the NodeList with forEach()

jQuery(document).ready(function($){
  document.querySelectorAll(".video-container video").forEach((video) => {
    video.addEventListener("mouseenter", () => {
      video.play();
    });
        
    video.addEventListener("mouseleave", () => {
      video.pause();
    });
  });
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much - this worked perfectly! I appreciate you sharing knowledge about NodeLists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.