Switch/toggle div (jQuery)

Jan picture Jan · Apr 15, 2009 · Viewed 107.6k times · Source

I wish to accomplish a fairly simple task (I hope!)

I got two div tags and one anchor tags, like this:

<a href="javascript:void(0);">forgot password?</a>
<div id="login-form"></div>
<div id="recover-password" style="display:none;"></div>

I wish use the anchor tag to toggle between the two div tags, hide the one and show the other and vice versa.

How can this be done the best way?

Answer

Christian C. Salvad&#243; picture Christian C. Salvadó · Apr 15, 2009

Since one div is initially hidden, you can simply call toggle for both divs:

<a href="javascript:void(0);" id="forgot-password">forgot password?</a>
<div id="login-form">login form</div>

<div id="recover-password" style="display:none;">recover password</div>

<script type="text/javascript">
$(function(){
  $('#forgot-password').click(function(){
     $('#login-form').toggle();
     $('#recover-password').toggle(); 
  });
});
</script>