</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/203198/event-binding-on-dynamically-created-elements" dir="ltr">Event binding on dynamically created elements?</a>
<span class="question-originals-answer-count">
(23 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-08-28 23:32:51Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
I'm trying to make a page with a box in three steps, and each step needs to be loaded by ajax, the steps change after each click in the button "next". I'm changing the class of the button for each step so I can load the next, do not know if there is a better method. but when I click to go to the second step carries me the first step.
/**** THIS WORK FINE *****/
// First Click on Next Button load first step
$('.next-button').on('click', function(){
$('.first-step').load('includes/selecione-torcida.html');
$('.next-button').addClass('next-torcida');
});
/**** THIS DON'T WORK *****/
// Second Click on Next Button load second step but in the class "next-torcida"
$('.next-torcida').on('click', function(){
$('.first-step').load('includes/selecione-amigos.html');
});
</div>
This is an example of a direct event handler, and it will only be applied to elements that exist at the DOM creation point.
You need to use a delegated event handler so it will bubble to the newly added elements (or in this case, the class you're assigning then wanting to bind to a click.
Here's an example of how to do it with delegation:
// Direct event, is only bound to elements existing at DOM creation point
$('.next-button').on('click', function(){
$('.first-step').load('includes/selecione-torcida.html');
$('.next-button').addClass('next-torcida');
});
// Delegated event, will listen for newly created elements too
$(document).on('click', '.next-torcida', function(){
$('.first-step').load('includes/selecione-amigos.html');
});
Basically, you tell jQuery to listen for clicks on all .next-torcida
elements that exist within the entire document, which includes all newly created elements too.
The direct way is that when the DOM is loaded, the event handlers are attached individually to each element that has the .next-button
class, so new elements created won't have the handler and you'd have to bind a new event handler when you create it.
Note: I've just used document
here as an example, that's pretty broad and it would be a good idea to narrow it down for performance reasons to the closest parent that all of those elements share.
Here's another post explaining the differences between direct and delegated.