9er
9er

Reputation: 1734

JQuery hover state for appended elements

I am writing a page that once loaded will go off and make an ajax call, process the json respose data, and then append these elements into the dom as shown in a simplified way below:

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

It should also be noted I am using Metafizzy's Isotope library. http://isotope.metafizzy.co/

To demonstrate my issue I have a <div class="article-block"></div> both in the DOM at load time and one more appended once the ajax call finishes.

this jquery will only capture the first and not the second though!

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

I've spent some time debugging this and found that when I type $('.article-block'); into the console. I get both correctly. However when I hover over my first one the fade works, and when I hover over the second, it doesn't.

Any ideas?

Upvotes: 1

Views: 94

Answers (1)

t3dodson
t3dodson

Reputation: 4007

Order matters

You are registering your event handler for the initial div when the page loads which is good. Its important to note that if you add dom elements later you will need to apply handlers to the new items.

Try saving a reference to your handlers and applying it later.

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

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

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

Upvotes: 1

Related Questions