user2763557
user2763557

Reputation: 439

How do I write get element by id using if statement so that when one button is clicked it shows the div and hides the rest?

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

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

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

Related Questions