theNeighbourhoodGhost theNeighbourhoodGhost - 2 months ago 11
jQuery Question

Toggle between 2 classes in jQuery

How can I toggle between two classes in jQuery, while the element does not have either class.

Please note: I want to know if there is a way to do this with the

toggleClass()
method and not by
addClass()
,
removeClass()
. For example:

$('#myDiv').click(function(){
$("#myDiv").toggleClass('red blue')
})

Answer

You could use function parameter of toggleClass() method:

$('#myDiv').click(function() {
  $(this).toggleClass(function(){
    return $(this).is('.red, .blue') ? 'red blue' : 'red';
  })
});

$('#myDiv').click(function() {
  $(this).toggleClass(function() {
    return $(this).is('.red, .blue') ? 'red blue' : 'red';
  })
});
.red {
  color: red;
}
.blue {
  color: blue;
}
#myDiv {
  -webkit-user-select: none;
  /* Chrome all / Safari all */
  -moz-user-select: none;
  /* Firefox all */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
  /* Likely future */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv">
  My DIV
</div>