Dynamically removeClass from the element but Click event still can be detected

Viewed 304

I have buttons look like this:

<a class="h-modal-btn branch-modal-btn"> Buy Now </a>

The scenario is that I want to remove class and add attributes to the buttons according to the query string passed by the URL. Omit the above steps, I just do

$('a.branch-modal-btn').removeClass('h-modal-btn');

When I check whether the class is removed by checking the developer tools. Well, the class is removed from the HTML. Great! But immediately I found that the code below is still executed.

$('.h-modal-btn').on('click', function() {
    // Do somthing
)}

That's so depressing! Please help me, I'll be appreciated.

2 Answers

This is because you have assigned the event listener to that button before you even remove the class. Now the event listener is already attached. Changing the classname like that will not help you to not trigger the listener anymore.

So you need to remove the listener manually from those elements. You can use unbind or the newer off method for this.

$('a.branch-modal-btn').off("click").removeClass('h-modal-btn');

Instead of:

$('.h-modal-btn').on('click', function() {
    // Do somthing
)}

use this:

$(document).on('click', '.h-modal-btn', function() {
    // Do somthing
)}

or you can use this:

$('a.branch-modal-btn').off("click").removeClass('h-modal-btn');
Related