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);
});
}
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:Edit: After thinking about it more and considering @Nemoden’s answer, you could also do it like this:
This would attach the click callback without having to use the ID at all.