Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a video play only on hover using html/css?

I have a page with a multiple columns of videos, of which I would wish to only play and sound on hover. Much thanks.

I have tried using the hover feature in css, yet to no avail.

like image 525
Durant Long Avatar asked Sep 14 '25 18:09

Durant Long


1 Answers

You need to use javascript for that. Assuming the videos are static, not dynamically added:

const videos = document.querySelectorAll('.video');

videos.forEach(video => {
  video.addEventListener('mouseenter', () => {
    video.play();
  });
  
  video.addEventListener('mouseleave', () => {
    video.pause();
    video.currentTime = 0;
  });
});

Here you are iterating through all video elements and adding an event listener. When mouse enters within the area of the element, the video is played. When mouse leaves, video stops and the seek position sets to start or 0.

like image 97
Fuad Hasan Avatar answered Sep 17 '25 07:09

Fuad Hasan