0

I'm trying to have multiple videos to hover over and start a preview video like youtube. Works so far, but only for one video, the first one. How do I make it play on hover for every video? (The videos are the same for testing)

HTML:

<div class="videos" onclick="location.href='video1.html'" style="cursor:pointer; position: relative;">
        <video>
            <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" />
        </video>
        <b>Video Title</b>
        <p>Video Description</p>
</div>
<div class="videos" onclick="location.href='video2.html'" style="cursor:pointer; position: relative;">
        <video>
            <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" />
        </video>
        <b>Video Title 2</b>
        <p>Video Description 2</p>
</div>

JS:

function delay(milliseconds){
            return new Promise(resolve => {
                setTimeout(resolve, milliseconds);
            });
        }
                
        const video = document.querySelector("video");
        
        async function startPreview() {
          await delay(300);
          video.muted = true;
          video.currentTime = 1;
          video.playbackRate = 0.5;
          video.play();
        }
        
        function stopPreview() {
          video.currentTime = 0;
          video.playbackRate = 1;
          video.pause();
        }
        
        let previewTimeout = 1000;
        
        video.addEventListener("mouseenter", () => {
          startPreview();
          previewTimeout = setTimeout(stopPreview, 4000);
        });
        
        
        video.addEventListener("mouseleave", () => {
          clearTimeout(previewTimeout);
          previewTimeout = null;
          stopPreview();
        });

When I change "document.querySelector" to "document.querySelectorAll", nothing will happen at all and the first video doesn't play when hovering anymore.

How it looks rn

  • 1
    *"When I change "document.querySelector" to "document.querySelectorAll", nothing will happen at all..."* You can't **just** do that. You also have to loop through the `NodeList` you receive. – T.J. Crowder Feb 27 '22 at 09:50
  • @T.J.Crowder Thanks, how can I do that? – Skyspartan149 Feb 27 '22 at 11:00
  • There are thousands of examples here on SO if you look. Literally, you just write a loop (`NodeList` instances are array-like, though they aren't arrays) or call `forEach` on the `NodeList`. – T.J. Crowder Feb 27 '22 at 11:04
  • @T.J.Crowder I appreciate it... I'm very new to js... how does that look look like? Maybe you can send me a little loop... I really can't find anything thats working – Skyspartan149 Feb 27 '22 at 11:40
  • There are examples [right there in the answers to the linked question](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return). – T.J. Crowder Feb 27 '22 at 11:46

0 Answers0