Massey
Massey

Reputation: 23

Assign click handler to newly appended elements

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)) +"'>&nbsp;</a> ")

    //.click(function(){showPopup(regions1[key].id);})

});

Upvotes: 2

Views: 119

Answers (2)

Lee
Lee

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)) +"'>&nbsp;</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

griegs
griegs

Reputation: 22760

You want to use the .live jQuery keyword.

http://api.jquery.com/live/

$('.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

Related Questions