JQuery hover effect for dynamically added elements

Currently, I am working on a webpage that will trigger an ajax call upon loading. The response data in JSON format will be processed and the elements will then be added to the DOM as shown below:

$.ajax({
  type: 'POST',
  url: "http://mysite.dev:32769/getallnews",
  success: function(data){
       $container.append(item)
        .isotope( 'appended', item );
  }
});

I would like to mention that I am incorporating Metafizzy's Isotope library. More information can be found here.

For demonstration purposes, there is a

<div class="article-block"></div>
present in the DOM initially, with another one appended after the ajax call completes.

The following jQuery code only works for detecting hover on the first div element and not the second:

$(".article-block").hover(function(){
  //hover on
  $(".article-block div").fadeIn();
},function(){
  //hover off
  $(".article-block div").fadeOut();
});

After spending time debugging, I observed that typing $('.article-block'); in the console displays both elements correctly. However, when hovering over the first one, the fade effect occurs, while it does not work for the second one.

Any suggestions or ideas on how to fix this issue?

Answer №1

Order of Operations is Key

When registering your event handler for the initial div upon page load, you are setting a solid foundation. Remember, it's crucial to consider that if new DOM elements are added later on, you will need to apply handlers to those new items as well.

Consider saving a reference to your handlers and applying them at a later time.

function hoverOn() {
    $(".article-block div").fadeIn();
}
function hoverOff() {
    $(".article-block div").fadeOut();
}

// initially on page load
$('.article-block').hover(hoverOn, hoverOff);

// Later in an AJAX call
$.ajax({
    type: 'POST',
    url: "http://mysite.dev:32769/getallnews",
    success: function (data) {
        $(item).hover(hoverOn, hoverOff); // Register your hover event for the new element.
        $container.append(item).isotope( 'appended', item );
    }
});

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

Using the Object.assign technique will modify the original object's properties in JavaScript

Recently delving into ReactJS, I stumbled upon an interesting revelation regarding the Object.assign() method: const B = { k1: 'b', k2: 'bb', treedata: [{ children: ['g'] }] } var A = Object.assign( ...

Tips for arranging images in a horizontal layout using FlatList in React Native

Is there a way to display feed images horizontally instead of vertically in FlatList? I've tried wrapping the images in a view with flex-direction set to row, as well as adding horizontal={true} to the FlatList, but nothing seems to work. Any suggesti ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

Vue and Jexcel: maximizing efficiency with event handling and dynamic calculations

I am trying to utilize the vue wrapper for jexcel and want to trigger the undo function from the toolbar computed field. However, I am facing difficulties accessing the spreadsheet instance as it throws an error saying 'this.undo is undefined.' ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

Creating diagonal background cutouts using CSS

Can you create a diagonal cut in a background color using CSS? Check out this example .item { color: #fff; font-size: 30px; background-color: #565453; padding: 10px 10px 10px 10px; width: 52%; text-align: center; display: inline-block; } ...

Loading Rails page with Ajax request

Is there a way to have an ajax function automatically called on page load in Rails using AJAX? For Example Let's look at the following example of an ajax call. <div id="result"><%= link_to item,blog_comments_path({:comment => "Hello", : ...

How to utilize AJAX to input data into a MySQL database using PHP in a multi-step form

Hi there, I'm currently working on a project that involves inserting data into a MySQL database using PHP and AJAX with multiple forms on a single page. The insertion process is functioning correctly, but I'm facing an issue where the data from ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

Creating a jQuery multiple image preview feature is a simple and effective way to

Looking to implement a single image upload preview function in jQuery? Want to modify it to allow for multiple image uploads with separate boxes? Check out the HTML script below. <!DOCTYPE html> <html> <head> <title></title> ...

Troubleshooting: Why is $watch failing to track changes on factory variables in Angular

I have created a factory named SharedService as shown below: angular.module('Fms').factory('SharedService', function() { var userdetails=false; return userdetails; }) Below controllers utilize this factory: angular.mod ...

Issue encountered: Failure to locate module 'socket.io' while attempting to execute a basic server JavaScript file

Below is my server.js file that I am attempting to run using node server.js: var app = require('express')(); var http = require('http').createServer(app); var io = require('socket-io')(http); //also tried socket.io instead of ...

I'm looking to adjust the padding on the left and right sides of the v-select menu checkbox in Vuetify 3. How

While trying to reduce the left padding of the v-select menu checkbox using the F12 debugger, I encountered an issue where the menu suddenly disappears when clicked. This makes it difficult to see the active menu. Attached is a screenshot of the select me ...

How can the overflow:hidden be applied to the body after a specified height, rather than the height of the viewport

My page has a <body> element with a height of 800px, however the content exceeds this height. I would like the body to display content up to 800px and then hide the rest, but using overflow:hidden hides all content beyond the viewport height of 678p ...

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...

When using @click as a link, it results in an

I'm attempting to create a clickable row in a datatable that functions as a link. Placing a standard <nuxt-link> within a <td> works fine, but wrapping the entire <tr> disrupts the table layout. Next, I tried using @click with a met ...

Tips for correctly identifying and sending the form name and submit button name when using AJAX for form submission

I need a concise solution to include the form name and submit button name along with the form input fields when sending data. I have attempted to use the form.serializeArray() method, but it only retrieves the input field names in the post data. Is there a ...

Utilizing Ajax to insert a line break within an alert message

I came across this link which explains that using \n can help achieve my goal. However, the method I am using does not seem to be working as expected. $.ajax({ url:'ajax/core/Ajax_Request.php', type:'POST', ...

React Error: Invalid Element Type with Named Exports

I've been diving into the world of React hooks and functions, working on three different files. First, there's one that establishes a context called SummaryContext. The second file contains a class component that consumes this context named WikiS ...