1

This is an example of my jQuery code that I use in a function to do pagination:

// new_content is a variable that holds the html I want to add to a div
$('div#my_div').html(new_content);
$("div#my_div a.details").hover(function(){         
    $(this).fadeIn(); //code to execute when the mouse get in
}, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
});  

BUT the hover event does not work at all, and I believe that this is caused because the DOM is not ready yet!

To get around this I used set up a timer like this:

$('div#my_div').html(new_content);

window.setTimeout(
  $("div#my_div a.details").hover(function(){           
    $(this).fadeIn(); //code to execute when the mouse get in
  }, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
  });
,100); 

I asked this question because I'm sure that this is not the right way to attach an event immediately after the html method (maybe it didn't it's work!).

si I hope someone show me the right way to do it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hidalgo
  • 765
  • 1
  • 9
  • 28

4 Answers4

2

You would want to use the live mouseover mouseleave events

$("div#my_div").live({
       mouseenter: function()
       {

       },
       mouseleave: function()
       {

       }
    }
);

Alternately you could do:

$('div#my_div').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
        // do something on mouseover
    } else {
        // do something on mouseout
    }
});

UPDATE

In newer versions of jQuery you can do it like this

$('body').on('mouseover','#my_div', function(){});
$('body').on('mouseout', '#my_div', function(){});
brenjt
  • 15,997
  • 13
  • 77
  • 118
2

Maybe you need to use the live() method. As you can read here, it seems that you will need to separate the two events:

.live("mouseenter", function() {...})
.live("mouseleave", function() {...});

UPDATE: Someone voted me up, so if someone gets here, I recommend to read the on() documentation (here) as live was deprecated long ago. Also, it may be interesting to see mouseenter()(link) and mouseleave() (link). The idea is the same as with live.

Community
  • 1
  • 1
Vithozor
  • 610
  • 10
  • 22
0

you can check out .live function of jquery. Here is the link http://api.jquery.com/live/

biluriuday
  • 428
  • 1
  • 7
  • 16
0

It is better to use a delegate rather than live, as live is essentially a delegate on the document.body causing it to have to bubble much longer.

Here is an example using a delegate: http://jsfiddle.net/Akkuma/wLDpT/

Akkuma
  • 2,215
  • 3
  • 16
  • 21
  • first Thank you, i just tried your example it's good i will look in the documentation for details. – Hidalgo Jul 13 '11 at 14:50
  • your code executes only the instructions in the else block, so i changed mouseenter by mouseover, & now it work perfectly. – Hidalgo Jul 13 '11 at 15:08