DEV Community

Cover image for Video preview on hover with HTML and JavaScript
Juan Belieni
Juan Belieni

Posted on

Video preview on hover with HTML and JavaScript

In this post, I will be showing how to add a preview feature for the videos inside your HTML page.

First, I will be using this simple HTML code as the base to create the preview feature:

<video>
  <source 
    src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
  />
</video>
Enter fullscreen mode Exit fullscreen mode

So, to start, we should create the startPreview and stopPreview functions. To contextualize, the preview will be played during 4 seconds, starting after the first second at a playback rate of 50%.

The startPreview will set the values so that the preview will be played as mentioned, and stopPreview will reset the values to the default ones.

const video = document.querySelector("video");

function startPreview() {
  video.muted = true;
  video.currentTime = 1;
  video.playbackRate = 0.5;
  video.play();
}

function stopPreview() {
  video.currentTime = 0;
  video.playbackRate = 1;
  video.pause();
}
Enter fullscreen mode Exit fullscreen mode

After it, we should create the event listeners so that the preview can be played on hover. To accomplish this, a timeout will be used to stop the preview after 4 seconds.

let previewTimeout = null;

video.addEventListener("mouseenter", () => {
  startPreview();
  previewTimeout = setTimeout(stopPreview, 4000);
});

video.addEventListener("mouseleave", () => {
  clearTimeout(previewTimeout);
  previewTimeout = null;
  stopPreview();
});
Enter fullscreen mode Exit fullscreen mode

It's important to clear the timeout every time the user leaves the video area, because it can happen that a previous timeout stops the video when the user enters the video area for a second time before the 4 seconds.


Here is the result:

Top comments (0)