jQuery Toggle State

neezer picture neezer · Oct 28, 2008 · Viewed 81.3k times · Source

Here's the quick and skinny of my issue:

$("a").toggle(function() { /*function A*/ }, function() { /*function B*/ });

Inside function A a form is displayed. If the user successfully completes the form, the form is hidden again (returning to it's original state).

Inside function B the same form is hidden.

The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding.

Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link twice before returning to the toggle state that displays the form.

Is there anyway to programmatically reset the toggle switch to its initial state?

Answer

Nicky Vandevoorde picture Nicky Vandevoorde · Dec 16, 2011

You can check the state of the toggle in jQuery by using .is(":hidden"). So in basic code what I used:

$("#div_clicked").click(function() {
  if ($("#toggle_div").is(":hidden")) {
     // do this
  } else {
     // do that
}
}); # add missing closing