tags:

views:

124

answers:

3

I'd like to have a text area on my page that shows a div and hides the others (let's say 8 other divs). On click, I'd like the chosen div to show and the current div & other divs to hide. Is there a simple solution to this? Possible to build off of: http://stackoverflow.com/questions/2509807/show-current-clicked-div-hide-previous-clicked-div ?

+2  A: 

How about something like this?

$(document).ready( function(){
  $('div.some_class').click( function(){ // set of divs to be clickable
    $(this).siblings('div').hide(); // it's already showing, right?
  });
});

Of course, once one is clicked and the others are hidden, you'll have no way of bringing them back...

Ken Redler
A: 

it depends on the DOM structure. I'd personally give them some class to have an easy access to the whole group. $('.div-group').hide(0, function(){$('#my-div').show();});

Consider using jQuery UI Accordion, which might be an answer to functionality you need.

migajek
+1  A: 

Here's a simple solution making use of chaining together methods.

$("input").click(function () 
{
    $("#" + $(this).attr("class")).show().siblings('div').hide();
});

jsFiddle example ( using $("input") )
jsFiddle example ( using $(".className") )

The activating buttons could have the same class as the id of the affected divs, or you can use a separate "toggler" class.

The important part is to use a unique feature of the clicked element to map to a unique feature of the toggled element.

Finally, if the toggling divs are not siblings, you can set up a selector of all of them using var divs = $("#blah1, #blah2, #blah3, ..."); and toggle them using .not().

jsFiddle example of non sibling toggling divs using .not()

Peter Ajtai
This worked fine - I used the .not() example and used img as my selector because my a.class was being used for another event. Thanks!
ShawnB
@ShawnB - Nice to hear. Don't forget to accept answers (the check mark below the votes) that solve your problems, and up vote answers you find useful.
Peter Ajtai