Issue with HTML5 Video Play on Hover Functionality Ceases to Work Upon Loading Dynamic Content

I recently implemented a feature on my WordPress site that allows videos to start playing when the mouse hovers over their thumbnails and pause when it leaves. However, I encountered an issue where this function works perfectly upon initial page load but fails to work with additional content loaded via ajax.

Although I'm still learning JavaScript, I have identified that my code ceases to function properly when new content is added dynamically through ajax. I've read about using an "on" state but struggle to integrate it with my current code structure.

$(document).ready(function() {
    var figure = $(".video").hover( hoverVideo, hideVideo );

function hoverVideo(e) {  
    $('video', this).get(0).play(); 
}

function hideVideo(e) {
    $('video', this).get(0).pause(); 
}
        });

I understand that the issue lies in the fact that the new content is not being recognized as "ready" or that the script lacks awareness of dynamically added elements due to missing page reloads. So, any suggestions on how to make this work seamlessly with dynamic content? Appreciate your help!

Answer №1

I managed to solve the problem on my own.

$(document).on({
    mouseenter: function () {
        $('video', this).get(0).play();
    },
    mouseleave: function () {
        $('video', this).get(0).pause();
    }
}, '.video');

By utilizing $(document).on rather than $(document).ready, it can be applied to any previously loaded or upcoming ".video" classes for customization.

The use of mouseenter and mouseleave events instead of .hover

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

Is it possible to use Vuelidate for password validation in Vue.js?

I found a helpful reference on How to validate password with Vuelidate? validations: { user: { password: { required, containsUppercase: function(value) { return /[A-Z]/.test(value) }, containsLowercase: fu ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

Challenges in working with PHP, SQL, HTML, and AJAX data submission

Having encountered another issue, I've been attempting to make an AJAX script function properly, but whenever I click on it, the page reloads without updating the database field. The code I'm using has successfully worked for similar scripts on ...

Issues with JQuery `.click()` event

Check out this snippet of code I'm working with: $(".item").click(function () { alert("clicked!"); }); I also have (hypothetically; in reality it's more complex) the following HTML on my page: <a href="#" class="item"> ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your tim ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Pass an array containing an HTML string to the $.post method in jQuery

I have a problem with displaying HTML content fetched from a PHP script using the jQuery $.post method: $.post('{$site_url}tests/tests/content', params, function (data) { $('#some-div1').html(data[1]); $('#some-div2').htm ...

Having trouble getting Vue-Select2 to display properly in Vuejs?

After setting up the vue3-select2-component and following their instructions, I encountered an issue where the component was not displaying in the output on the html page, even though the code for it was present in the source code. For context, I am using ...

Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the ...

What is the method for assigning a class name to a child element within a parent element?

<custom-img class="decrease-item" img-src="images/minus-green.svg" @click="event => callDecreaseItem(event, itemId)" /> Here we have the code snippet where an image component is being referenced. <template&g ...

Django is unable to establish sessionid Cookies due to Webpack's restrictions

After setting up my React application with Webpack and Django for Backend, I encountered an issue with session authorization. Whenever I attempt to make a request, I receive a 200 OK status Response, but the session-id is visible in the Set-Cookie header, ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

Collaborating with an array and leveraging ajax operations

I'm working with an array of objects and trying to display them all on the page using Ajax when a link is clicked. run.js.erb $(function(){ $("#next").click(function(){ $.post(<%= EngineHelper.nextQuestion %>, function(data){ $("#q ...

How can I remove a specific JSON object from localStorage based on the data associated with the element that is currently being clicked on?

Unique Scenario A user interacts with an element, triggering a change in the background image and storing data related to that element in localStorage: this process functions correctly. Next, the toggle variable is set to 0, the background image change ...