jQuery UI toggleClass

Overview

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.

Dependencies

  • Effects Core

Example

Adds the 'selected' class if it is not present, and removes the 'selected' class if it is present.

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

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
  <script src="http://ui.jquery.com/latest/ui/effects.core.js"></script>
<style type="text/css">
  p { cursor: pointer; font-size: 1.2em; }
  .selected { color:red; }
</style>
  <script>
  $(document).ready(function() {
    $("p").click(function () {
      $(this).toggleClass("selected", 1000);
    });
  });
  </script>
</head>
<body style="font-size:62.5%;">
  
<p>Click me to toggle 'selected' class.</p>
<p class="selected">Click me to toggle 'selected' class.</p>
<p>Click me to toggle 'selected' class.</p>

</body>
</html>

Arguments