Reputation: 439
So on click of one of these buttons I want to hide the rest and just show the div belonging to the button that is clicked. I.e if I click allButton everything shows. If i click onButton, only the online Div shows, vice versa for offButton.
My online div is under class 'onlineWrapper' and my offline div is under class 'offlineWrapper'.
I want to write an if statement combined with get element by id (if that is a good way) to do this, instead of individually writing .hide() or .toggle() for each button.
What is the best way I can do this on jquery?
<div class="btn-group">
<button class='allButton'>All</button>
<button class='onButton'>Online</button>
<button class='offButton'>Offline</button>
</div>
Upvotes: 0
Views: 30
Reputation: 33933
I think you don't need any comparison to do what you described... Just an event handler for each button. See below:
$(".onButton").on("click",function(){
$("#onlineWrapper").show();
$("#offlineWrapper").hide();
});
$(".offButton").on("click",function(){
$("#onlineWrapper").hide();
$("#offlineWrapper").show();
});
$(".allButton").on("click",function(){
$("#onlineWrapper").show();
$("#offlineWrapper").show();
});
#onlineWrapper, #offlineWrapper{
border: 1px solid black;
padding:1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
<button class='allButton'>All</button>
<button class='onButton'>Online</button>
<button class='offButton'>Offline</button>
</div>
<div id="onlineWrapper">Online div</div>
<div id="offlineWrapper">Offline div</div>
Upvotes: 1