Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change div by clicking on same link

I have #div1 and #div2. #div is visible by default while #div2 is hidden. When clicking a link, I want to hide #div1 and display #div2, when clicking again on the link I want to hide #div2 and show #div1 again.

With the following jQuery I can hide first div and display #div2, but I don't know how to display #div1 when clicking again on the same link. Also how can I switch the link title according to the visible div (ie. switch to div1 or div2)

HTML:

<a class="switch" href="#">Switch to Div 2</a>

<div id="div1">Div1</div>
<div id="div2">Div2</div>

jQuery:

$(".switch").click(function() {
  $('#div1').hide();
  $('#div2').show();
});

CSS:

#div2 { 
   display: none; 
}

Demo: http://jsfiddle.net/De4x2/

like image 696
user2738640 Avatar asked Dec 19 '22 22:12

user2738640


1 Answers

Try toggle():

http://jsfiddle.net/94bUG/

$(".switch").click(function() {
  $('#div1, #div2').toggle();
  // the following line switches the text
  $(this).text('Switch to Div ' + ($('#div1').is(':visible') ? '2' : '1'));
});
like image 193
Jason P Avatar answered Jan 03 '23 20:01

Jason P