« Back to UI/Effects

[edit]

toggleClass( class, [duration] )

Adds the specified class if it is not present, and removes the specified class if it is present, using an optional transition.
Arguments:
classString
A CSS class to toggle on the elements.
duration (Optional)String, Number
A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

Examples:
Toggle the class 'highlight' when a paragraph is clicked with a one second transition.

    $("p").click(function () {
      $(this).toggleClass("highlight", 1000);
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script src="http://dev.jquery.com/view/tags/ui/latest/ui/effects.core.js"></script>

  <script>
  $(document).ready(function(){
    
    $("p").click(function () {
      $(this).toggleClass("highlight", 1000);
    });

  });
  </script>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder; 
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }
  </style>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
</body>
</html>

NameType