I have several divs which should be shown / hidden when the corresponding button is clicked. In the initial state all buttons and all divs are visible. When the first button is clicked, only the corresponding div should be visible. When the second button is clicked, the corresponding div should be visible as well etc. The click on a button should toggle the state of the button and the corresponding div.
I’m not sure if this can be realized without placing a cookie or local storage token. So far I’ve created the following code, which only allows me to deactivate the divs with one first click.
$(function() {
$('.button').click(function(){
$(this).toggleClass('inactive');
$('#mydiv'+$(this).attr('target')).toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class="button" target="1">Button 1</button>
<button class="button" target="2">Button 2</button>
<button class="button" target="3">Button 3</button>
</div>
<div id="mydiv1">
<p>Div 1</p>
</div>
<div id="mydiv2">
<p>Div 2</p>
</div>
<div id="mydiv3">
<p>Div 3</p>
</div>
3
Answers
You’d have to initially hide the divs and show the correct one when the right button is clicked.
If you want to toggle only the button/div that you just clicked, first you have to reset previous state of all elements to initial (remove class
inactive
and show all divs) and only than toggle state.Have you to use a toggle or you can also solve it with a walk around?