How to use toggleclass() Method and toggleclass () using function method in JQuery

In this article, I will explain use of toggleclass () Method and how to use toggleclass () method using function in JQuery.
  • 2095

Introduction

toggleClass() method features add or remove one or more class from selected elements.

JQuery CSS toggleClass() method

The toggleClass() method toggles between adding and removing one or more classes for the selected elements.

Syntax

$(selector).toggleClass(class,switch)

  • class classname is Required parameter, we can add several classes.

  • Switch switch can specify to only remove, or only add a class.

Example

The following example shows how to toggleClass() method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            $("p").toggleClass("toggle");

        });

    });

</script>

<style type="text/css">

.toggle

{

font-size:150%;

color:blue;

}

</style>

</head>

<body>

<h3>toggleClass() Method Example</h3>

<p>First paragraph.</p>

<p>Second paragraph.</p>

<button>Click for see Toggle effect</button>

</body>

</html>

 

Output


toggle simple.jpg

JQuery CSS toggleClass() using function method

toggleClass() using function specify which classes should be toggled for the selected elements.

Syntax

$(selector).toggleClass(function(index,class),switch)

toggleClass(function(index,class)) returns one or more class names to add/remove.

  • index -get the index position of the selector
  • class - get the current class of the selector

Example

The following example shows how to toggleClass() using function method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            $("li").toggleClass(function (n) {

                return "itemlist_" + n;

            });

        });

    });

</script>

<style type="text/css">

.itemlist_1, .itemlist_3

{

color:Maroon;

}

.itemlist_0, .itemlist_2

{

color:blue;

}

</style>

</head>

<body>

<h1>toggle() using function example</h1>

<ul>

<li>C#</li>

<li>ASP.NET</li>

<li>SQL SERVER</li>

<li>HTML/CSS</li>

</ul>

<button>Click for add/remove classes</button>

</body>

</html>

 

Output

 

toggle function.jpg

Further Readings

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2013 dotNetheaven. All rights reserved.