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>
$(function() { $('#showdiv1'). click(function() { $('div[id^=div]'). hide(); $('#div1'). fadeIn(3000); }); $('#showdiv2').
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With