Undefined Variable
Undefined Variable

Reputation: 4267

how to execute function on dynamically added element?

I have an ajax post function in jquery. The response of the ajax call is passed to a handler that generates a bunch of div elements like so:

function handleResponse(data)
{
        $.post( 
            "ajax.php",
            { 
                url: url,
                action: "getProductImages" 
            },
            function(data) 
            {
                var obj = jQuery.parseJSON(data);
                newDiv = "";
                jQuery.each(obj, function(key,value) 
                {
                    newDiv += '<div class="product-img-container">\
                    <img src="'+value+'"></div>';
                });
                $("#product-images").empty();
                $(newDiv).appendTo('#product-images');
            }
}

As you can see I create new divs with class product-img-container and render them inside product-images div.

Now I want to run this code on these newly created divs:

$('.product-img-container').productThumb(); 

I tried putting this inside $(document).ready function,but it does not work there because the divs are not available at that time. I then put this inside my handleResponse function, as:

....
$("#product-images").empty();
$(newDiv).appendTo('#product-images');
$(newDiv).productThumb();

Doesn't work either :(

Upvotes: 0

Views: 68

Answers (1)

Stryner
Stryner

Reputation: 7318

newDiv is just a string. When you call $(newDiv), jQuery is creating the DOM elements for you.

The code you tried is doing the following:

// Create DOM elements and append to #product-images
$(newDiv).appendTo('#product-images');

// Create DOM elements and attach events. 
// These DOM elements are different! You never attach them to the DOM.
$(newDiv).productThumb();

Instead you should create them and use that reference:

var $newDiv = $(newDiv);
$newDiv.appendTo('#product-images');
$newDiv.productThumb();

Or you could simply chain them:

$(newDiv).appendTo('#product-images')
         .productThumb();

Upvotes: 2

Related Questions