K.K. Smith
K.K. Smith

Reputation: 992

Attaching event listener to dynamically generated image in jQuery?

I am adding images to my page dynamically with jquery. Basically I am creating "pixel-y / lo-res" versions of the images on the page, and adding the at page load overtop of the originals. Then a typical "fade-out on hover" thing should fade them out on mouseover, showing the orignals.. as if "up - rezing" .. if that makes sense.

So I've got the images coming in.. but somehow the hover listener isn't attaching. At first I tried hover, now I'm on click just because it is easier to troubleshoot. Nothing.

The .on() function should attach itself even to dynamically added items, right? What is going wrong? I'm not getting any errors. It's just not working.

$.ajax({
        type:"POST",
        url:"js/pixelsandwich/pixelsandwich.php",
        data:{src:src},
        success:function(response){  // if there is already a "lo-rez" image, I get that URL.. if there isn't, one is created and I return that URL
            newImg = $("<img class='crunched'>"); // create the new <img>
            newImg.attr('src', response); // assign the source
            frame = $that.parent(); // grab the containing frame
            frame.append(newImg);  // add the new image.  css:position:absolute and z-index take care of the rest
        }
    });

$(".crunched").on("click", function(){  // << this just isn't attaching at all
     alert("hello");
    $(this).fadeTo('slow',0.5);
});

Cn anyone help?

Upvotes: 0

Views: 1956

Answers (2)

user1726343
user1726343

Reputation:

The on method should be used to delegate event handling to an extant ancestor of the dynamically added elements. For example:

$(document).on("click", ".crunched", function(){  // << this just isn't attaching at all
     alert("hello");
    $(this).fadeTo('slow',0.5);
});

The collection $(".crunched") is empty when you run your code, so the event handler isn't being attached to anything.

Upvotes: 0

j08691
j08691

Reputation: 208031

The .on() function should attach itself even to dynamically added items, right?

Nope, with dynamically created elements you have to bind using .on() to an element that already exists when the code is run. Worst case is usually the body element, but the closer an element you can pick in the DOM the better.

Assuming that .crunched is the class of your dynamically added elements, try:

$("body").on("click", ".crunched", function(){  // << this just isn't attaching at all
     alert("hello");
    $(this).fadeTo('slow',0.5);
});

Per the jQuery docs:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

Upvotes: 2

Related Questions