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?
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:
Per the jQuery docs: