Source
Source

Reputation: 1011

Adding a class, then removing it and adding another

So I want to add a class on click, and then when it is clicked again, I want to revert it back to the previous class. How is this achieved. I have also tested it using on(), but no luck there either.

$('.red').click(function() {
  $(this).removeClass('red').addClass('blue');
});

$('.blue').click(function() {
  $(this).removeClass('blue').addClass('red');
});
.red {
  color: red;
}

.blue {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="red">test click</a>

You can run the code here

How can I change the class back? It shows in the Dom, but not in the front end.

Upvotes: 0

Views: 46

Answers (2)

Istiaque Ahmed
Istiaque Ahmed

Reputation: 6488

For newly created elements or classes, .click as you used will not work. You have to use on method in the following way :

$(document).on('click','.red', function(){

                $(this).removeClass('red').addClass('blue');
            });


 $(document).on('click','.blue', function(){

                $(this).removeClass('blue').addClass('red');
            });

Upvotes: 0

guradio
guradio

Reputation: 15555

  1. Use .toggleClass()
  2. Since button are having dynamic class use .on() for dynamically added elements

$(document).on('click', '.red', function(e) {
  e.preventDefault();
  $(this).toggleClass('red blue');
});

$(document).on('click', '.blue', function(e) {
  e.preventDefault();
  $(this).toggleClass('red blue');
});
.red {
  color: red;
}

.blue {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="red">test click</a>

Upvotes: 3

Related Questions