0

I have a div in which an unordered list is being loaded into, dynamically. First, let me say that when the ul is hardcoded in, it works perfectly, the problem occurs when a new ul is loaded. Here's my javascript:

$('#products ul li').hover(function(){
   $(this).find(".productDesc").fadeToggle("slow");
});

The html of the code that is dynamically loaded into <div id='products'></div> is structured like so:

<ul id='category1'> 
  <li>
     <p class='productDesc'>description 1 here</p>
  </li>

  <li>
     <p class='productDesc'>description 2 here</p>
  </li>
</ul>

The problem lies in "this". When the new UL is dynamically loaded, "this" no longer seems to refer to the element I'm hovering on. Instead, it seems to refer to nothing at all. What can I do to make "this" work properly?

user2755541
  • 536
  • 2
  • 10
  • 25

2 Answers2

1

You need to use event delegation since li the elements are added dynamically.

Since you are using hover, there is no hover event - it is a utility method to register both mouseenter and mouseleave events

$('#products').on('mouseenter mouseleave', 'ul li', function () {
    $(this).find(".productDesc").fadeToggle("slow");
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • OP could also bind directly to the elements as they're created, which is sometimes more desirable than delegation for events that fire repeatedly, like `mouseenter/leave`. – cookie monster Mar 31 '14 at 15:46
  • Yes, that's it! I don't really understand the theory behind it, but it definitely fixed the problem. What about the .delegate method on jp310's answer? How are they different? – user2755541 Mar 31 '14 at 15:49
  • @user2755541 there is not much difference... `.on()` is the new method (>=1.7) where as delegate is there from 1.4.2... but new codes the recommended method is `on` – Arun P Johny Mar 31 '14 at 15:52
1
$('#products').delegate('ul li','hover', function( event ) {
    if( event.type === 'mouseenter' )  
        //your code here 
    else
        //your code here  
});
cookie monster
  • 10,671
  • 4
  • 31
  • 45
pj013
  • 1,393
  • 1
  • 10
  • 28