Reputation: 23
How does one go about adding a click handler in the following example? I need to assign it to the newly appended anchor element.
$.each(regions1, function(key, value) {
var coords = regions1[key].rel.split('-');
$("#map").append("<a href='javascript:void(0)' id='"+ regions1[key].id +"' class='bullet' style='left: "+ addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)) +"; top: "+ addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset)) +"'> </a> ")
//.click(function(){showPopup(regions1[key].id);})
});
Upvotes: 2
Views: 119
Reputation: 13542
Try this:
$.each(regions1, function(key, value) {
var coords = regions1[key].rel.split('-');
// first, create the element
var element = $("<a href='javascript:void(0)' id='"+ regions1[key].id +"' class='bullet' style='left: "+ addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)) +"; top: "+ addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset)) +"'> </a> ");
// then add the listener/handler
element.click(function(){showPopup(regions1[key].id);})
// finally, append the new element to the dom.
$("#map").append( element );
});
Upvotes: 1
Reputation: 22760
You want to use the .live jQuery keyword.
$('.bullet').live('click', function() {
// Bound handler called.
});
This sample, btw, needs to sit outside any of your other code and placed within the $(document).ready jQuery method. It will bind a click event to all items that have a class of "bullet".
Upvotes: 3