Change div by clicking on the same link

I have #div1and #div2. #divdisplayed by default while #div2hidden. When I click on the link, I want to hide #div1and show #div2when I click the link again, which I want to hide #div2, and show again #div1.

With the following jQuery, I can hide the first div and display #div2, but I do not know how to display #div1when I click on the same link again. Also how can I switch the link name according to the visible div (i.e. 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/

+4
source share
1

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'));
});
+11

All Articles