3

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.

hayley
  • 384
  • 5
  • 17
  • Does this answer your question? [JavaScript CSS how to add and remove multiple CSS classes to an element](https://stackoverflow.com/questions/1988514/javascript-css-how-to-add-and-remove-multiple-css-classes-to-an-element) – نور Aug 10 '20 at 05:54
  • @AbdullahAlNoor Sorry, that's not the answer that I need :( – hayley Aug 10 '20 at 06:01
  • 1
    removing a CSS class doesn't removes any event listeners. You will need to remove the listener explicitly. – Yousaf Aug 10 '20 at 06:04

2 Answers2

5

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');
The Fool
  • 16,715
  • 5
  • 52
  • 86
  • 1
    Not sure who down-voted - But +1 from me for a good answer. – Always Helping Aug 10 '20 at 06:12
  • or he could put the event listener to a ancestorial element, that way it should listen for changes - like `$('.someAncestorElementClass').on('click', '.h-modal-btn', function(){})` AKA delegated event. but the end result is the same i guess, just another way of doing it. +1 from me – Stender Aug 10 '20 at 07:42
1

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');
Abolfazl Mohajeri
  • 1,734
  • 2
  • 14
  • 26