jQuery toggleClass() Tutorial – POFTUT

jQuery toggleClass() Tutorial

jQuery javascript framework provides the toggleClass() method in order to toggle between different classes for the specified elements. The toggle will simply remove the old class and add a new class to the specified elements like button, label, div, etc.

jQuery toggleClass() Method Syntax

toggleClass() method is provided by the jQuery and in order to call the toggleClass() method the selector shouldbe used by selecting an element like div, button, label etc.

  • SELECTOR is the jQuery selector that will select single or multiple items where the toggle operation will be applied.
  • CLASSNAME specifies one or more class names to add or remove. Multiple class names can be added by separating them with spaces. CLASSNAME is required.
  • FUNCTION(INDEX, CURRENTCLASS) is optional and specifies a function that returns one or more class named to add or remove.
  • SWITCH is an optional parameter where a boolean value true or false is specified to add or remove. true will be specified to add class and false will be specified to remove.

jQuery toggleClass() Examples

In the following example we will change use the selector to select buttons and toggle its class to the test.

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

<div class="text collapsed">some text</div>

    $('.switch-btn').on('click', function(e) {
      $('.text').toggleClass("collapsed"); //you can list several class names 

LEARN MORE  Introduction to Javascript Programming Language

Leave a Comment