On hover, add an img or video specified in data-src to a separate div

I have a several div’s that have either an img or video URL specified using a data- attribute. Like so <div class="swiper-slide" data-src="img/content/1-landscape.jpg">

When these div’s on hovered over the image/video should be added to and displayed in another separate div. The image/video will update depending on which div is hovered over.

<div class="carousel-bg">
    <img src="" />
    <video autoplay muted loop>
        <source src="" type="video/mp4">

I’m aware it’s probably not great to have these empty tags on the page, a better way might be to add the entire img or video element when required but this is just where I’m at right now!

My UI is a bit more complex than the following example but I’ve stripped out everything else just the focus on the fundamentals of the script. This example shows the image working, however I haven’t been able to workout the if/else to check if it’s a image or video and add to the relevant tag.

I tried to work in the following (below) without any luck. And also tried adding a class .onload so I can fade in/out the media when ready - but I’ll come back to that.

const media = item.querySelectorAll(“img, video”)
item.onmouseover = () => media.src = media.dataset.src;

Once the correct image/video is displayed. There’s a few other things I need to think about (for reference)…

  • These files could be quite large (not as large as the images in the example), so should I be displaying a loading animation then only fade-in the image or video when it’s ready?
  • I won’t need this on mobile/tablet as there’s no hover event. So will just run the script when touch is not detected.

Thanks in advance!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.