Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery events doesn't work for appended elements

I have this site here

As you can see there is a tiny image slider for "Images" and "Web Templates" tabs where the images are sliding from right to left, then disappears and then it appears at the very end of the parent element (an <tr> in my case).

If you hover over the small images you can see it's preview on the left.

So far so good.

But if you wait until the first images comes again, the hover event doesn't work anymore.

It is possible that jquery can't see that new appended elements at the end of the <tr> tag?

like image 962
Ionel Lupu Avatar asked Jun 01 '12 20:06

Ionel Lupu


3 Answers

The way you are binding your events will not work for dynamically added elements. In preview_script.js you have:

$(".box_body img").hover(function(){

This will add eventhandlers to all img tags with class "box_body", but ones that are appended later will NOT get the event.

Try this:

$(document).on("hover", ".box_body img", function() {..});

This will add the event to document, and only fire it if the eventtarget is img with class = "box_body". Since events propagate up this should work as long as nothing in between stops it before it reaches document (by calling "event.stopPropagation()")

If you know the PARENT of ".box_body img" you can replace document with that, this will work a little better as you don't have to wait for the event to propagate up to document.

Note that you can accomplish the same thing using delegate (if on is not available):

$(document).delegate(".box_body img", "hover", function() {..});
like image 186
Porco Avatar answered Oct 14 '22 03:10

Porco


You will want to use the .live() function of jQuery in order to attach event handlers to elements that will be created in the future. Here's the doc: http://api.jquery.com/live/ here's usage:

$(".dynamicButtons").live("hover", function() {
    //do stuffs
});
like image 2
solidau Avatar answered Oct 14 '22 03:10

solidau


In your script.js change file here http://web-art.netau.net/script.js

$(".box_body img").hover(function(){
            var src=$(this).attr("src");
            var target=$(this).parents("table").attr("id").split("_").pop();
            $("#preview_"+target).attr({src:src});
})

line 112 to 116 to the following

$(document).on('mouseenter',".box_body img",function(){
        var src=$(this).attr("src");
        var target=$(this).parents("table").attr("id").split("_").pop();
        $("#preview_"+target).attr({src:src});
});

The reason behind this has been answered many times in SO. Search and find a good answer. Like

Event binding on dynamically created elements?

In jQuery, how to attach events to dynamic html elements?

jquery binding events to dynamically loaded html elements

like image 2
Prasenjit Kumar Nag Avatar answered Oct 14 '22 03:10

Prasenjit Kumar Nag