Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens with the handlers when you change the innerHTML property

Ok lets say I have

<div id="container"/>

and I put a button in this container with id = "button". Then I make .click handler for it

$("#button").click(function() {
foo();
}

Then I change the innerHTML of the div like this:

$("#container").html = "<h1> Foo </h1>";

Then I set timer for let's say 5 seconds that after that will execute the following code :

function(){
$("#container").html = "<button id="button" type="button">Click Meh!</button>"
$("#button").click(function() {
foo();
}
}

My question is: The first button was "destroyed", so was the first .click() handler for it destroyed too? Or the second .click() will just make a second handler for the same button and if I want to have only 1 handler I have to use $("#button").off("click") before calling the second .click() ?

like image 533
chnging Avatar asked Oct 16 '25 09:10

chnging


1 Answers

  1. Yes, when you removed the element (by overwriting the html of the element), you've disassosciated the click handler with the element.

  2. Instead, we should just be looking at delegating the event. We target a static parent element (like container), and delegate the event to it:

$('#container').on('click', '#button', foo);

Now when the button is clicked, we'll fire off the foo function. Even if you remove the button and add it later, the event will still be delegated to '#container'.

like image 82
Ohgodwhy Avatar answered Oct 18 '25 22:10

Ohgodwhy