DEV Community

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

Posted on

21 2

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:

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay