Reputation: 10626
html code:
<div id="all"> </div>
<div id="div1"> </div>
<div id="div2"> </div>
<div id="div3"> </div>
<div id="div4"> </div>
<div id="div5"> </div>
jquery code:
This works for swithcing between "div1" and "all". What if I wanted to click on #div1 and show only "all" and hide the others and when clicked on "all", show all the divs.
$(function () {
$("#div1, #all").on('click', function ()
{
$("#div1, #all").not(this).show();
$(this).hide();
});
});
Upvotes: 1
Views: 5835
Reputation: 79830
Try below approach using class
.
HTML:
<div id="all"> </div>
<div class="myDivs"> </div>
<div class="myDivs"> </div>
<div class="myDivs"> </div>
<div class="myDivs"> </div>
<div class="myDivs"> </div>
JS:
$(function () {
$('.myDivs').click (function () {
$('.myDivs').not(this).hide();
});
$('#all').click (function () {
$('.myDivs').show();
});
});
Edit: Improvised with 2 handlers
DEMO: http://jsfiddle.net/Fsg9y/2/
Upvotes: 3
Reputation: 23796
I'm assuming your divs won't actually be named "div1", div2, etc. In which case, you could do this:
$(function(){
$("div").click(function(){
if ($(this).attr("id") === "all"){
$(this).siblings().show();
}
else{
$(this).siblings().not("#all").hide();
}
});
});
Upvotes: 0
Reputation: 3745
You could use something like the following:
(function($) {
$('div[id^=div]').click(function(){
var id = $(this).attr('id');
$.each($('div[id^=div]'), function() {
if ($(this).attr('id') == id) return true;
$(this).hide();
});
});
$('div#all').click(function() {
$('div[id^=div]').show();
});
})(jQuery);
Upvotes: 0
Reputation: 6752
Here's what you need to do, using lovely selectors that jQuery provides
$(function () {
$('div[id^="div"]').click(function() {
$(this).siblings().filter(':not(#all)').hide();
});
$('#all').click(function() {
$('div[id^="div"]').show();
});
});
Upvotes: 4
Reputation: 12635
You could do this via the foreach function and providing the parent node's id:
$('div').each( function() {} );
Upvotes: 0