Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery onclick toggle class name

Tags:

jquery

Using jQuery, how do I toggle classA to classB on click going from:

<a class="switch" href="#">Switch</a>
<div class="classA"></div>


$('.switch').on('click', function(e){
    $('.classA').removeClass('classA').addClass('classB');
    e.preventDefault();
};

How do I toggle the class, instead of just replacing it like I'm doing here?

like image 937
cusejuice Avatar asked Mar 26 '13 01:03

cusejuice


People also ask

What does toggleClass return?

toggleClass( function [, state ] ) A function returning one or more space-separated class names or an array of class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the state as arguments.

How do you toggle with multiple classes?

Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.

How do I toggle between two classes in JavaScript?

JavaScript Toggle Class Multiple Elements You can also toggle class on multiple element at once. For this target multiple elements and use the toggle() method. To toggle a class on multiple elements select those elements and apply the toggle method on each element to handle their corresponding class.


2 Answers

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>
like image 58
Matt Zeunert Avatar answered Oct 18 '22 20:10

Matt Zeunert


you can use toggleClass() to toggle class it is really handy.

case:1

<div id='mydiv' class="class1"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class2"></div>

case:2

<div id='mydiv' class="class2"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class1"></div>

case:3

<div id='mydiv' class="class1 class2 class3"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class3"></div>
like image 28
Arun Pratap Singh Avatar answered Oct 18 '22 20:10

Arun Pratap Singh