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

Avoid triggering a second event: click versus changing the URL hash

One of the pages on my website has tabs that load dynamic content: HTML <ul> <li><a href="#tab-1">TAB 1</li> <li><a href="#tab-2">TAB 2</li> <li><a href="#tab-3">TAB 3</li> </ul&g ...

"Utilize HTML to make inline-block elements appear small in size while giving the illusion of being

I have a group of inline-block elements (4 total), all arranged neatly in a single row. As the window size changes, the elements wrap to the next line accordingly. The page does not display scrollbars at the bottom until the browser width reaches the minim ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

jquery events such as onSubmit, onComplete, etc. are commonly used

It's interesting to observe that many tools in jQuery, especially those involving ajax, contain hooks like onSubmit, onComplete, and more. Is there a specific term for this practice and the standards associated with it? Does this practice belong sol ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

Encountering an "undefined" error while implementing a registration system in Node.js and attempting to retrieve

Having recently delved into the world of javascript and nodejs, I am currently working on developing a registration system. The issue I'm facing is related to an error message indicating that "isEmail" is undefined. I have included my form validator a ...

Failed commitments in Protractor/WebDriverJS

WebdriverIO and Protractor are built on the concept of promises: Both WebdriverIO (and as a result, Protractor) APIs operate asynchronously. All functions return promises. WebdriverIO maintains a queue of pending promises known as the control flow to ...

The basic jQuery script is failing to function properly in the Opera browser

I've encountered an issue with a simple jQuery script I wrote. It seems to work fine on most browsers, except for Opera. Can anyone help me figure out what the problem might be? jQuery(document).ready(function() { jQuery("input:radio[name=virtuem ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Making changes to a database model (updating or replacing)

When making changes to a model in the database, is it more efficient to only update a specific field or replace all objects at the same level with that field? ...

I'm trying to create a transparent v-card, but for some reason it's not turning out the way I want

How can I make the v-card transparent while keeping its content opaque using CSS? card.vue <v-card class="cardColor"> <v-card-text> TEXT </v-card-text> <v-card-actions> <v-btn color="prima ...

The X axis labels are missing on the Google column chart

Problem: All column charts are rendering correctly in Internet Explorer. However, Upon clicking the "View Build Performances" button, project names are displayed on the x-axis of the first three column charts only. The other column charts do not show pro ...

Show the div just one time

Hey there, I'm trying to create a StackOverflow-like message display at the top of my page. Everything is set up and configured, but I'm facing an issue - the message only shows up the first time. After that, it disappears. I've read that ...

What sets apart computed, state, and action in MobX?

Currently, I am delving into MobX and grappling with the concepts of computed, state, and action individually. Do they serve similar purposes? One aspect of MobX that intrigues me is deciphering the disparity between computed properties and state. My unde ...

Activating a function on a click or item selection in React using Office UI Fabric's

<div> <CommandBar areNamesVisible={false} areIconsVisible={true} items={[ { name:"James Towns", className:"noHoverEffect", }, { key:"Info", icon:"Contact", onItemClick={this.handlePanel} ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...