I tried making a thumbnail to play a YouTube video when I hover and stop playing when I stop hovering on it, but it doesn't stop when the mouse isn't hovering on it. Here's the code:
<div class="thumbnail" data-video-id="D9N7QaIOkG8">
<img src="assets\meyra.jpg" alt="Thumbnail 1">
<div class="video-overlay"></div>
</div>
<script>
function onYouTubeIframeAPIReady() {
const thumbnails = document.querySelectorAll(".thumbnail");
thumbnails.forEach(function(thumbnail) {
const videoOverlay = thumbnail.querySelector(".video-overlay");
const videoId = thumbnail.dataset.videoId;
thumbnail.addEventListener("mouseenter", function() {
const player = new YT.Player(videoOverlay, {
videoId: videoId,
width: "100%",
height: "100%",
playerVars: {
autoplay: 1,
controls: 0,
rel: 0,
showinfo: 0
}
});
videoOverlay.style.display = "block";
});
thumbnail.addEventListener("mouseleave", function() {
videoOverlay.innerHTML = "";
videoOverlay.style.display = "none";
});
});
}
</script>
I want the YT video to stop playing when I stop hovering on the thumbnail
As noted in the comment by @sohaieb azaiez, you are not stopping the player. Insert this line in in the listener for mouseleave
:
player.pauseVideo()
The whole function should be:
thumbnail.addEventListener("mouseleave", function() {
player.pauseVideo()
videoOverlay.innerHTML = "";
videoOverlay.style.display = "none";
});
Please read the YouTube Player API reference, there are many other methods and working examples.