ShawnB
ShawnB

Reputation: 143

How can I show div on click, hide the others with jQuery?

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: show current clicked div hide previous clicked div ?

Upvotes: 4

Views: 11545

Answers (3)

Peter Ajtai
Peter Ajtai

Reputation: 57685

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()

Upvotes: 3

migajek
migajek

Reputation: 8614

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.

Upvotes: 0

Ken Redler
Ken Redler

Reputation: 23943

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...

Upvotes: 2

Related Questions