Gallery · 29 of 33

Video Hover

Plays video on hover (replaces image)

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="video-hover" id="videoHover"
  data-video="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4">
  <img src="https://picsum.photos/id/200/800/600" alt="Video Placeholder">
  <div class="video-container" id="videoContainer"></div>
</div>

CSS

.video-hover {
  position: relative;
  width: 400px;
  aspect-ratio: 4 / 3;
  overflow: hidden;
  border-radius: 12px;
  background: #000;
}

.video-hover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  position: relative;
  z-index: 1;
  transition: opacity 0.3s;
}

.video-hover:hover img {
  opacity: 0;
}

.video-container video {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  object-fit: cover;
}

JavaScript

var wrap = document.getElementById('videoHover');
var container = document.getElementById('videoContainer');
var src = wrap.dataset.video;
var video = null;

wrap.addEventListener('mouseenter', function () {
  // Lazily create the video on first hover
  if (!video) {
    video = document.createElement('video');
    video.src = src;
    video.loop = true;
    video.muted = true;
    video.playsInline = true;
    container.appendChild(video);
  }
  video.play().catch(function () {});
});

wrap.addEventListener('mouseleave', function () {
  if (video) {
    video.pause();
    video.currentTime = 0;
  }
});