JQuery show div on click, hide others

I would like to have a text area on my page that shows a div and hides the rest (albeit 8 other divs). On click, I would like the selected div to show, and the current div and other divs to be hidden. Is there a simple solution? You can build: show the current click on the div hide the previous click on the div ?

+4
source share
3 answers

Here's a simple solution using methods of combining with each other.

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

JsFiddle example (using $ ("input"))
JsFiddle example (using $ (". ClassName"))

Activating buttons may have the same class as id for the affected divs, or you can use a separate toggler class.

An important part is to use the unique function of the clicked element to map to the unique function of the switchable element.

Finally, if the switching divs are not siblings, you can adjust the selector of all of them using var divs = $("#blah1, #blah2, #blah3, ..."); and switch them using .not() .

JsFiddle example to switch without sibling divs using .not()

+3
source

How about something like that?

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

Of course, as soon as one is clicked and the rest are hidden, you will have no way to return them ...

+2
source

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

Consider using jQuery UI Accordion, which may be the answer to the functionality you need.

0
source

All Articles