I have multiple div’s on my page, that can be added to the page dynamically, and can also be removed.
On page load, the dynamically created div’s are loaded from localStorage with uniqiue id’s and a common class depending on the div, and I call a function along with that, content().
The function content() looks like this:
function content(){
alert("test");
$(".two button").click(function(){
var id = $(this).parent().attr("id");
alert(id);
});
}
Pretty simple, all it does is alert “test” when the function is called, and if you click .two <button>, it will alert .two <textarea> .val().
This works fine once the div’s have been loaded, but I run into the problem when I clone the div’s
When I clone the div’s, it gives them a unique id and a common class like above. At the end of cloneDiv(), I call content(), so that clicking on the elements inside will produce the same results as above.
The problem is, the function will get called as many times as there are div’s on the screen, but also means that clicking on the <button> in div .two will alert .two <textarea> .val() three times.
TLDR; Clicking on the button in .two get’s called as many times as there are div’s on the screen, as the function is called once the dynamic div is created, but should only be called once.
There’s a lot of code to do all this, but I think I explained what happens pretty clearly. I will however whip up a demo if that would help more.
This is what “event delegation” is for. You set up a handler on the document and it will handle events from its descendants, even if they are created after the handler is attached: