How can you achieve the effect of "hovering over an image to automatically start playing a muted video within the image itself"?

[![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>

Answer №1

Give this method a try

<script>
  var videoElement = document.getElementById("myVideo");
  var imageElement = document.getElementById("hoverimage");
  var containerElement = document.getElementById("image-video-container");

  containerElement.addEventListener("mouseover", function () {
    imageElement.style.display = "none";
    videoElement.style.display = "block";
    videoElement.currentTime = 0;
    videoElement.play();
  });

  containerElement.addEventListener("mouseout", function () {
    videoElement.pause();
    imageElement.style.display = "block";
    videoElement.style.display = "none";
  });

  // expand video to full screen and play when clicked on parent element
  containerElement.addEventListener("click", (event) => {
    if (containerElement.requestFullscreen) 
      containerElement.requestFullscreen();
    else if (containerElement.webkitRequestFullscreen)
      containerElement.webkitRequestFullscreen();
    else if (containerElement.msRequestFullScreen) 
      containerElement.msRequestFullScreen();
    videoElement.muted = false;
  });
</script>

The concept involves hiding the image when hovering over the parent div, displaying the video instead. When the mouse leaves, the video is hidden again and the image reappears.

For a demonstration, check out this live codesandbox example

Answer №2

Start by ensuring that the image and video have the same dimensions so they appear properly at the same size.

Create a container sized based on the dimensions of the image and video, and use overflow: hidden to prevent them from overflowing outside the container.

#image-video-container {
  position: relative;
  height: 400px;
  width: 400px;
  overflow: hidden;
}

You can also utilize object-fit: cover; to make the image/video fill the container. For example:

#image-video-container img {
  position: relative;
  object-fit: cover;
  height: 100%;
  width: 100%;
  display: block;
}


#image-video-container video {
    position: relative;
    display: none;
    object-fit: cover;
    height: 100%;
    width: 100%;
}

Check out this jsfiddle example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

The @media feature is not functioning properly

I am struggling with getting my media query to function properly on a school project. Despite carefully checking my code, I cannot figure out why it is not making the desired changes when viewed on a mobile device. If anyone has any suggestions or insigh ...

Styling an HTML table with two columns: one column displaying an image, and the other column containing information related to the image

I have a concept that involves creating a table with 2 columns. The left column will feature an image, while the right column will display data about the image in 6 rows. ________________________________ | |_______________| | | ...

What is the best way to utilize XPATH effectively within scrapy?

Explore more here Check out this link too: https://i.stack.imgur.com/8bhzV.png If you are struggling with finding the red marked box number, take a look at the image on this link: https://i.stack.imgur.com/mca05.png Don't worry, I have provided my ...

Is it possible to determine the outcome of a JavaScript function using Python?

I am currently in the process of creating a web crawler. Extracting links from HTML is simple, but finding links that are generated by JavaScript proves to be more challenging for me. Is there a way to access the JavaScript output in order to determine w ...

What is the most effective way to save numerical information to a file?

Imagine a scenario where there is an array filled with one million random numbers: [ 0.17309080497872764, 0.7861753816498267, ...] The task at hand is to store these numbers onto a disk for future retrieval. While storing them in text formats like JSON or ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

Looking for a particular table element using Selenium Webdriver in Java: A Guide

After locating a table element using this: WebElement tableElement = selectorboxelement.findElement(By.xpath("//ancestor::table")); I identified the `selectorboxelement` as a web element with this line of code: WebElement selectorboxelement = driver.fin ...

What is the best way to create a mirrored effect for either a card or text using CSS

Can anyone assist me with this CSS issue? When I hover over to view the movie details, the entire word flips along with it. Is there a way to make only the word flip initially, and then have it return to normal when hovered? The HTML code is included belo ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

The issue persists as AJAX data and text box data are not being saved simultaneously

I need assistance with an Ajax setup. I am trying to pass the screenwidth information along with a user input value from a text box to a PHP page. However, I am encountering issues as the only value being passed is from the textbox and the other one is sho ...

issue with jquery fade toggle not working properly on Bootstrap website

My website is built using Bootstrap and jQuery. I am facing an issue where the fadeToggle() function on a div element is not displaying properly - it remains hidden all the time. Can anyone provide insight into what might be causing this problem, or sugg ...

Manipulating input dates in AngularJSIn AngularJS, we can easily set the value

I'm having trouble setting a date field in my code. Despite trying to follow the example provided in the AngularJS documentation, nothing is showing up in the "departure" field. Here is what I have: HTML: <input type="date" name="departure" ng-mo ...

When utilizing webpack in Angular 5, the :host selector does not get converted into a component entity

Initially, I set up Angular with webpack following the configuration in this guide, including configuring webpack sass-loader. Everything was working smoothly until I encountered an issue today: app.component.ts @Component({ selector: 'ng-app&ap ...

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Discovering how to use the selenium-webdriver npm to navigate to a new window from a target="_blank" attribute

While trying to create a collection of selenium tests, I encountered an obstacle with the javascript selenium-webdriver npm package. One specific test involves selenium verifying that a target="_blank" link functions properly by checking the content of th ...

To prevent the background image (blue border) from shifting, I need to extract the list item element without causing the image to

Having trouble with the side borders on my navbar. I've used a background image for the border (blue line) in the list item of the navbar. Is there a way to move down two specific list items slightly, like shown in my screenshot? I need to bring down ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and document. ...

Laravel's Vue component is experiencing issues with loading Axios response data

Hey everyone, I hope you're all doing well! I'm facing a bit of an issue with passing data from an axios response to the data property. The data is successfully fetched from the database and displayed in the console, but when I try to display it ...