0

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');
   });
Cristiano Matos
  • 329
  • 1
  • 2
  • 10

1 Answers1

2

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.

Community
  • 1
  • 1
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • Thanks perfect explanation, but this way I would be clicking a button for the two steps and always carries the first step (next-button). Thanks. – Cristiano Matos Aug 28 '14 at 23:24
  • You could remove the next-button class once you have added the next-torcida class? I hadn't noticed this, but it's not a great idea to have two event handlers attached to an element – scrowler Aug 28 '14 at 23:27