Romi
Romi

Reputation: 4921

How to add an onclick event to a dynamic generated div

I have a number of divs in my HTML file that are dynamically generated. When I add the divs, I want to add an onclick event to each div.

Each div has a dynamic id. Using id, how can add an onclick handler?

Code that generates divs:

function createSlider(resp) {
    $.each(resp, function(key, val) {
        var item = "<div class='item' id="+val.id+">";

        item += "<h2>" + val.category + "</h2>";
        item += "<img src=" + val.image + " alt=" + val.title + ">";
        item += "</div>";

        $(".content-conveyor").append(item);
    });
}

Upvotes: 3

Views: 17364

Answers (3)

Rohan Patil
Rohan Patil

Reputation: 2348

.live() is used to attach handlers to DOM elements that may not yet exist in the DOM. After $(".content-conveyor").append($item); add following code.

 $('#' + val.id).live(click,function() {
 // your code here
 });

Upvotes: 1

You can apply the click function to the ID after you append it to the dom. So, after your $(".content-conveyor").append(item); line, add this:

$('#' + val.id).click(function() {
// Do stuff on click
});


Edit: After thinking about it more and considering @Nemoden's answer, you could also do it like this:

function createSlider(resp) {
    $.each(resp, function(key, val) {
        var item = "<div class='item' id="+val.id+">";

        item += "<h2>" + val.category + "</h2>";
        item += "<img src=" + val.image + " alt=" + val.title + ">";
        item += "</div>";
        var $item = $(item).click(function() {
            // Add on click code here
        });
        $(".content-conveyor").append($item);
    });
}

This would attach the click callback without having to use the ID at all.

Upvotes: 7

alwynd
alwynd

Reputation: 311

You could use the class name of the div for an event handler on all elements that match that class name.

$(".item").click(function() {
    //
 });

Upvotes: 1

Related Questions