Toggle More Than Two CSS Classes Of An Element - toggleClasses.js

Toggle More Than Two CSS Classes Of An Element - toggleClasses.js

toggleClasses.js is an extension to the jQuery .toggleClass() method that enables you to sequentially switch multiple CSS classes of an element. 

1. Load the minified version of the toggleClasses plugin after loading jQuery JavaScript library.

<script src="https://code.jquery.com/jquery-3.3.1.js" 
        integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous">
</script>
<script src="toggleClasses.min.js"></script>

2. Call the function on the element and define an array of CSS classes to swtich between.

<div class="foo">A</div>
<div class="foo">B</div>
<div class="foo">C</div>
.myClass1 {
  background-color: #C0392B;
}
.myClass2 {
  background-color: #3498DB;
}
.myClass3 {
  background-color: #16A085;
}
$('.foo').on('click', e => {
  $(e.target).toggleClasses(['myClass1', 'myClass2', 'myClass3']);
});

3. Decide whether to add the initial class of the element to the loop.

$('.foo').on('click', e => {
  $(e.target).toggleClasses(['myClass1', 'myClass2', 'myClass3'], true);
});

This awesome jQuery plugin is developed by ThibaultJanBeyer. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 26.12.2018
  • Source