• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 404
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

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