• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 397
  • Last Modified:

jQuery: Toggle more than once

How can I toggle an item more than once?

In the example below, if you click on a blue box it should turn red, and if you click on a red box it should turn blue.

The problem is that my code will only allow you to change each item once.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style type="text/css">
a.maximize {display: block; width: 44px; height: 44px;background:  red;cursor: pointer;}
a.minimize {display: block; width: 44px; height: 44px;background: blue;cursor: pointer;}
</style>
</head>
<body>

<h1>Click a red item to make it blue.</h1>
<h1>Click a blue item to make it red.</h1>

 <p>
  <a class="minimize"></a>
 </p>

 <p>
  <a class="maximize"></a>
 </p>

<script type="text/javascript">
/* <![CDATA[ */

$('.minimize').click(function() {
  $(this).removeClass('minimize');
  $(this).addClass('maximize');
  $(this).attr('title','Minimize');
});

$('.maximize').click(function() {
  $(this).removeClass('maximize');
  $(this).addClass('minimize');
  $(this).attr('title','Maximize');
});

/* ]]> */
</script>
</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
2 Solutions
 
Greg AlexanderLead DeveloperCommented:
You can use the live() function to keep the click event bound to the new classes created
$('.minimize').live('click',function() {
  $(this).removeClass('minimize');
  $(this).addClass('maximize');
  $(this).attr('title','Minimize');
});

$('.maximize').live('click',function() {
  $(this).removeClass('maximize');
  $(this).addClass('minimize');
  $(this).attr('title','Maximize');
});

Open in new window

0
 
David S.Commented:
Those event handlers are added once to each element. When you change the class, the event handler is not changed too.

Try this:
$('.minimize, .maximize').click(function() {
  $(this).toggleClass('minimize maximize');
  if($(this).hasClass('minimize')) $(this).attr('title','Minimize');
  else $(this).attr('title','Maximize');
});

Open in new window

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now