[![enter image description here][1]][1]I am working with WordPress and Elementor, and I want to create a hover effect where an image triggers a muted video to play within the image area on mouseover. The video should stop playing when the mouse is not hovering over the image, and clicking on the image should allow the video to play in full screen. How can I achieve this using JavaScript? I tried asking for help in chat but did not get a working solution:
<script>
var myVideo = document.getElementById("myVideo");
var myImage = document.getElementById("hoverimage");
var container = document.querySelector(".image-video-container");
container.addEventListener("mouseover", function() {
myVideo.play();
});
container.addEventListener("mouseout", function() {
myVideo.pause();
});
</script>
The above code snippet is not functioning as expected.
With the assistance of @피케_ and @Madan Bhandari, I was able to make it work. The updated code is as follows:
<div id="image-video-container" style="
position: relative;
height: 300px;
width: 400px;
overflow: hidden;
">
<img
id="hoverimage"
style="
position: relative;
height: 300px;
width: 400px;
overflow: hidden;
"
src="https://www.deliverystone.com/wp-content/uploads/2023/03/IMG_20230222_145146_1.jpg"
/>
<video style="
position: relative;
display: none;
object-fit: cover;
height: 100%;
width: 100%;
"
id="myVideo" loop="" muted="">
<source
src="https://www.deliverystone.com/wp-content/uploads/2022/11/Aloha-Heja-He-BGM.mp4"
type="video/mp4"
/>
</video>
</div>
<script>
var myVideo = document.getElementById("myVideo");
var myImage = document.getElementById("hoverimage");
var container = document.getElementById("image-video-container");
container.addEventListener("click", (event) => {
if (container.requestFullscreen){ container.requestFullscreen();
myVideo.muted = false;}
else if (container.webkitRequestFullscreen){
container.webkitRequestFullscreen();
myVideo.muted = false;}
else if (container.msRequestFullScreen){ container.msRequestFullScreen();
myVideo.muted = false; }
});
container.addEventListener("mouseover", function () {
if (!document.fullscreenElement) {
myVideo.muted = true;
}
myImage.style.display = "none";
myVideo.style.display = "block";
myVideo.currentTime = 0;
myVideo.play();
});
container.addEventListener("mouseout", function () {
myVideo.pause();
myImage.style.display = "block";
myVideo.style.display = "none";
});
</script>