user1471980
user1471980

Reputation: 10626

clicking on a div to show and hide other divs in jquery

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

Answers (5)

Selvakumar Arumugam
Selvakumar Arumugam

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

aquinas
aquinas

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();
        }
    });       
});​

http://jsfiddle.net/mPdCb/1

Upvotes: 0

Sean3z
Sean3z

Reputation: 3745

You could use something like the following:

http://jsfiddle.net/sAW36/

(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

Bryan
Bryan

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

L0j1k
L0j1k

Reputation: 12635

You could do this via the foreach function and providing the parent node's id:

$('div').each( function() {} );

Upvotes: 0

Related Questions