Swaroop Nagendra
Swaroop Nagendra

Reputation: 605

Modifying attributes dynamically using jquery

Here is a part of an HTML page:

<div class="ajax-load">

</div>

<button id="next" class="load-page-2">

And here is the javascript:

$(".load-page2").click(function() {
    $(".ajax-load").load("3.php");
    $.get('4.php', function(data) {
         $('.ajax-load').append(data);
             $.get('5.php', function(data){
                $('.ajax-load').append(data);
            });
        });

     // Now I need to change the class of the #next button

    $("#next").removeClass("load-page2");
    $("#next").addClass("load-page3");
}); // End click function



//Now different functionality for the same button but with class "load-page3" 

$(".load-page3").click(function(){
    // load 6.php 7.php 8.php
});

But this does not work. It seems like the button still has the "load-page2" class and hence loads 3.php 4.php and 5.php

Upvotes: 0

Views: 52

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Since you are dealing with dynamic properties you need to use event delegation

$(document).on('click', '.load-page2', function(){
    //you code
})
$(document).on('click', '.load-page3', function(){
    //you code
})

When you add normal event handlers, those are attached to elements which matches the selectors at the time of the code execution, any changes made to the element attributes after that will not affect the registered handlers.

Upvotes: 1

Related Questions