Creating an event within a class that is generated dynamically when hovering

I'm trying to create a hover effect where an image moves around the page in a pattern (top left corner -> top right corner -> bottom right corner -> bottom left corner -> then back up to the top left corner).

To achieve this, I am adding and removing classes like hoverleft, right, down, up, etc. However, I'm facing an issue where the dynamically added classes are not recognized after the page loads. I've been attempting to use the .on() function but haven't had much success. I believe I may be overlooking something simple.

Here's my code in HTML and JS: you can also view it on jsfiddle here: http://jsfiddle.net/5w0nk6j9/4/

<div class="bodycontainer">
<div id="kim">
    <div id="dance" class="dancingkim">
    <div class="header">
        <h2 class="introheader">Hover original</h2>
    </div>
        <img src="http://placehold.it/240x208" />
</div>
</div>

$('#kim').hover(function(){
    $(".header h2").text("Hover text");
    });
    $('#kim').hover(function(){
    $(".dancingkim").css("cursor", "pointer");
});

$('.dancingkim').hover(function(){
    $(this).addClass("hoverleft");
    $(this).removeClass("dancingkim");
});

$('#kim').on('hover', '.hoverleft', function() {
    $('#dance').addClass("hoverdown");
    $('#dance').removeClass("hoverleft");
});

Answer №1

Instead of using hover, consider utilizing mouseover, mouseenter, or mouseleave.

$('#kim').on('mouseover', '.hoverleft', function() {
    $('#dance').addClass("hoverdown");
    $('#dance').removeClass("hoverleft");
});

According to the JQuery source code, hover is not listed as an event that triggers the use of JQuery .on()

Answer №2

One way to reference dynamically generated elements is by using the .on() method, which should be implemented on the document body. This allows the JavaScript to traverse the entire document and add the specified property to it.

Instead of:

$('#kim').on('hover', '.hoverleft', function() {
$('#dance').addClass("hoverdown");
$('#dance').removeClass("hoverleft");
});

Try this approach:

$('body').on('mouseover', "#kim", function(){
$(this).next().addClass("hoverdown");
$(this).next().removeClass("hoverleft");
});

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

Issue with Ag-Grid's getRowClass not locating the appropriate CSS styling

I am facing a simple challenge at the moment. My goal is to dynamically change the background color of my rows, with the intention of incorporating this feature when expanding or contracting groups. Currently, I am attempting to utilize gridOptions.getRow ...

Error occurs when an arrow function is called before its function definition

console.log(addB(10, 15)); function addB(a, b) { return a + b; } console.log(addC(10, 15)); const addC = (a, b) => { return a + b; }; I attempted to convert a function into an arrow function and encountered the error "Cannot access 'addC&ap ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

Troubleshooting issue with ng-change function in AngularJS

I have been working on developing a web application that includes two dropdown lists. My goal is to update the data in dropdown list 2 whenever there is a change in dropdown list 1. <tr> <td> State </td> <td> ...

Randomize.js feature following the completion of an asynchronous request

I recently started using a library called Shuffle, which can be found at . It works well for me, but I am currently facing an issue with implementing a load more button to load additional images. The functionality is based on Ajax, however, after making t ...

If the SASS condition matches the variable for the background color, then

I attempted to create a conditional statement in my component using Sass @if and @else. The condition I set was that if background == var(--bg-danger), the color should be white. However, it only returned white and did not trigger the else condition. @mixi ...

Issue: Module 'ansi-styles' not found when using AngularJS and Yeoman generator

Previously my code was functioning perfectly, but now it seems to have suddenly stopped working. Attempting yo angular:route api resulted in the following error message: Error: Cannot find module 'ansi-styles' at Function.Module._resolveFilen ...

Tips for displaying a success message following PHP form submission:

Check out this code. Here's what I'm looking to achieve -- User submits form --> Redirects to page2.php --> Redirects back to page1.php with message displayed (Could be a pop-up or something similar) Contents of page1.php: <form actio ...

Following the parsing of the list of months, the sequence undergoes a

After receiving the JSON encoded object from the server side in PHP MONTHLY_FORMAT, I am reading that object in jQuery as: var MONTHLY_FORMAT = '<?php echo $MONTHLY_FORMAT; ?>'; When checking the console output, it looks like this: {"0 ...

Try uploading a file with the imageUpload function in JavaScript, could be something basic

Today I successfully uploaded a picture using a basic button (id: "imageUpload") to select and upload a file. Everything worked flawlessly, with the thumbnail of the picture appearing in "thumb1." Now, I am attempting to allow users to upload a picture by ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

A step-by-step guide on utilizing jQuery to cyclically change the background color of elements upon clicking, and resetting the colors upon clicking another element

So I've been working on a solution to change the background color for accessibility purposes on a client's website. To achieve this, I have a set of div elements with different background colors and I'm using jQuery to update the body backgr ...

IframeResizer.js is automatically readjusting its position to the top left corner (0,0) when a javascript event or

Within our internal web environment, I have implemented IframeResizer.js in a rather basic manner. The child page contains a table generated by a third-party application with mouseover/hidden and javascript tags associated with the TH elements (including a ...

difficulty with parsing JSON in jQuery when referencing an external file containing the same data

Looking for help with parsing a json file using jquery? Check out this working sample: http://jsfiddle.net/bw85zeea/ I'm encountering an issue when trying to load "data2" from an external file. The browser keeps complaining that it's an invalid ...

A modern web application featuring a dynamic file treeview interface powered by ajax and php technology

Currently, I am developing a web-based document management system that operates as a single page using an ajax/php connection. The code snippet below shows how I display folders and files in a file tree view: if (isset($_GET['displayFolderAndFiles&apo ...

Encase children within a view component in React Native

I've been working on the following code: renderActionButtons(actionButtons){ let actionButtonsContent = actionButtons.map((button, i) => { return <TouchableHighlight key={i} onPress={() => {this.updateConversation(button);}} style= ...

Jquery refuses to load

Hey everyone! I'm currently working on an HTML file for my Angular 2 course. After setting up the dependencies and downloading them with npm, I encountered an error when trying to run the app... The error message I received was: file:///Users/Rocky/A ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

Ways to showcase angular scope data within a placeholder while avoiding the use of angular expressions

Initially, I utilized angular expressions {{value}} to present values within elements. However, upon noticing that unrevealed expressions continue to display on the front end during loading delays, I switched to using ng-bind. <div> <h1>Hell ...

Choose options from the month dropdown menu using Selenium WebDriver

Presently focused on working with Selenium WebDriver and Java. I am attempting to pick an option from a date picker form. When trying to select the month from the dropdown of the date picker, an error is displayed stating Unable to locate element: {"method ...