I am developer a website in Ruby on Rails. I have a page where I display the videos that I retrieve from the database. Video links are saved in the database and I retrieve them in my controller. In my view, I am trying to display all the videos and play part of the video on hover. The issue that I am facing is that, only first video is played on hover. All other videos are not played. I am using Javascript to add hover effect. Here is snippet of my view:
<% @clips.each do |clip| %>
<video width="200px" height="200px">
<source src=<%= clip.custom_video_link%>>
</video>
Here is my Javascript code:
<script>
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();
}
let previewTimeout = null;
video.addEventListener("mouseenter", () => {
startPreview();
previewTimeout = setTimeout(stopPreview, 4000);
});
video.addEventListener("mouseleave", () => {
clearTimeout(previewTimeout);
previewTimeout = null;
stopPreview();
});
</script>
Javascript code:
var figure = $(".video").hover( hoverVideo, hideVideo );
function hoverVideo(e) {
$('video', this).get(0).play();
}
function hideVideo(e) {
$('video', this).get(0).pause();
}
HTML code:
<div class="video">
<video class="thevideo" loop preload="none" width="200px" height="200px">
<source src="[insert source here]" type="video/[insert video type here]" />
</video>
</div>
This should work, let me know if it doesn't and I will try and help you some more.