Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide Multiple Divs with Jquery

Tags:

I want to use some buttons to show/hide multiple divs using jquery.

The page will initially show all divs. The idea then is that there will be a button to reset (show all) and then separate buttons to show a particular div while hiding the rest.

Any help would be much appreciated.

<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">Lorum Ipsum</div>
<div id="div2">Lorum Ipsum</div>
<div id="div3">Lorum Ipsum</div>
<div id="div4">Lorum Ipsum</div>
like image 687
Paul Avatar asked Aug 06 '11 13:08

Paul


People also ask

How to hide and show multiple div in jQuery?

$(function() { $('#showdiv1'). click(function() { $('div[id^=div]'). hide(); $('#div1'). fadeIn(3000); }); $('#showdiv2').

How to hide div in HTML based on condition?

If you want to hide the element when it's empty, look at the CSS :empty pseudoclass in conjunction with display: none. Otherwise you would need to use Javascript to evaluate your conditions and change the CSS value for display or visibility.


2 Answers

If they fall into logical groups, I would probably go with the class approach already listed here.

Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:

$("#div1, #div2, #div3").show();

Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.

like image 45
Dan Esparza Avatar answered Sep 19 '22 06:09

Dan Esparza


jQuery(function() {
  jQuery('#showall').click(function() {
    jQuery('.targetDiv').show();
  });
  jQuery('.showSingle').click(function() {
    jQuery('.targetDiv').hide();
    jQuery('#div' + $(this).attr('target')).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <a id="showall">All</a>
  <a class="showSingle" target="1">Div 1</a>
  <a class="showSingle" target="2">Div 2</a>
  <a class="showSingle" target="3">Div 3</a>
  <a class="showSingle" target="4">Div 4</a>
</div>

<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
<div id="div4" class="targetDiv">Lorum Ipsum4</div>

http://jsfiddle.net/XwN2L/

like image 192
Praveen Prasad Avatar answered Sep 19 '22 06:09

Praveen Prasad