-2

I added content by html() function. The contents have elements like images and links, but I can't use click or any function for the added content using its id.

Example:

$("#container").mouseover (function(){
    $("#container").html('<a id="button1" href="#"><img src="images/button1.gif"></a>');
});
$("#button1").click(function(){
    $("#container").html ('any content'):
});

1 Answers1

1

Events that are bound to elements BEFORE the element exists in the DOM will not register unless the event listener is delegated. For example, using jquery's .on(), you can add an event listener to the body tag and delegate the event to the added element:

// pretend "#button1" was appended to the DOM after this Javascript was parsed

// This would NOT work
$("#button1").click( function () {
   // do something
}

// This WOULD work
$("body").on("click", "#button1", function () {
    // do something
});

Your other option is to attach the event listener after the element is appended, but delegating is probably a better choice.

joshboley
  • 1,143
  • 6
  • 10