jQuery: The Write Less, Do More JavaScript Library

Attributes/toggleClass

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Attributes

toggleClass( class )

Adds the specified class if it is not present, removes the specified class if it is present.
Arguments:
classString
A CSS class to toggle on the elements.

Examples:
Toggle the class 'highlight' when a paragraph is clicked.

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("p").click(function () {
      $(this).toggleClass("highlight");
    });

  });
  </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