soum
soum

Reputation: 1159

single div to trigger toggle

Hi All I am trying to create a scenario where every time I click 'switch' I toggle between '#one', '#two' and '#three'

I can't figure out how to start the jquery

<div class="switch">swicth</div>
<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>

<style>
#one, #two, #three{
    display:none;
}
</style>

Upvotes: 0

Views: 137

Answers (4)

dfsq
dfsq

Reputation: 193291

A little magic:

$('.switch').click(function() {
    var c = $.data(this, 'index', ($(this).data('index') || 1) % 3 + 1);
    $('div').hide().eq(c-2).show();
});

Demo: https://tinker.io/0d614

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I would use class selector which will allow you to have any number of such div's.

DEMO: http://jsfiddle.net/m7gSn/2/

<div class="switch">swicth</div>
<div id="one" class="myc">1</div>
<div id="two" class="myc">2</div>
<div id="three" class="myc">3</div>  
<style> .myc { display:none; } </style>

JS:

var $myc= $('.myc');
var cp = 0;

$('.switch').click (function () {       
   $myc.hide().eq(cp++).show();       
   if (cp == $myc.length) cp = 0;        
});

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45155

I came up with this. After adding a class of toggle to the divs you want to rotate between:

$(".switch").click(function() {
    var toggle = $(".toggle:visible");
    if (toggle[0]) {
       $(toggle[0]).hide();
       var next = $(toggle[0]).next(".toggle");
       if (next[0]) {
         $(next[0]).show();   
       }
       else {
         $(".toggle").first().show();
       }
    }
    else {
        $(".toggle").first().show();
    }        
});

Demo

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

Try this:

$(".switch").toggle(
    function() { hideAll(); $("#one").show(); },
    function() { hideAll(); $("#two").show(); },
    function() { hideAll(); $("#three").show(); }
);

function hideAll() {
    $("#one, #two, #three").hide();
}

Example fiddle

Upvotes: 4

Related Questions