'How to open a div with button click and closing all other divs at the same time in jQuery
How can I show a specific div element with a button click and close all other elements at the same time in jQuery?
For example, I tired:
$('.button').each(function(i) {
$(this).click(function() {
$('.details').eq(i).slideToggle("slow")
$('.button').eq(i);
});
});
.details {
background: grey;
display: none;
}
.is-open {
display: block;
}
<!-- language: lang-html -->
<button id="button0" class="button">button 1</button>
<button id="button1" class="button">button 2</button>
<button id="button2" class="button">button 3</button>
<div class="details" id="details0">
<h1>Details Person 1</h1>
</div>
<div class="details" id="details1">
<h1>Details Person 2</h1>
</div>
<div class="details" id="details2">
<h1>Details Person 3</h1>
</div>
But this only toggles one elements without closing the others. But I want to close every opened element by clicking the one which isn't opened already.
I tried it with the suggested siblings() method but this did not apply for my case because I have my button elements separated from the button elements.
What is the best solution to achieve such an effect described above?
Solution 1:[1]
Do you want to implement the tab? https://jqueryui.com/tabs/
$('.button').each(function (i) {
$(this).click(function () {
$('.details').eq(i).show("slow").siblings('.details').hide();
});
});
Solution 2:[2]
Here is my solution:
$('.button').each( function(index,button){
//console.log(button.outerHTML);
$(button).click(function(){
let id=this.id.replace("button","");
$(".details").hide()
$("#details"+id).show();
})
});
.details {
background: grey;
display: none;
}
.is-open {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button0" class="button">button 1</button>
<button id="button1" class="button">button 2</button>
<button id="button2" class="button">button 3</button>
<div class="details" id="details0">
<h1>Details Person 1</h1>
</div>
<div class="details" id="details1">
<h1>Details Person 2</h1>
</div>
<div class="details" id="details2">
<h1>Details Person 3</h1>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rookie |
| Solution 2 | The KNVB |
