Reputation: 5
I have created an accordion, but I want it to close the tabs when another one is clicked. At the moment, it opens the tabs, but when another is clicked, it doesn't close the last one...
This is the code:
<button class="accordion">Accordion</button>
<div class="panel">Content</div>
<button class="accordion">Accordion 2</button>
<div class="panel">Content</div>
Upvotes: 0
Views: 2511
Reputation: 234
Just "close" all accordion pages in the click event.
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
var elems = document.getElementsByClassName("accordion");
for(var it of elems) {
it.classList.remove("active");
it.nextElementSibling.style.maxHeight = null;
}
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
Upvotes: 2
Reputation: 6555
use below Accordion and download first js and css on giving path on link in html
$( "#accordion" ).accordion({event:false, active :false});
var noSections = $("#accordion h3").length-1;
$("h3").each(function (index, element)
{
$(element).click(function()
{
if($(this).hasClass('ui-state-active'))
{
if(index < noSections)
$("#accordion").accordion('option','active',index + 1);
else
$("#accordion").accordion('option','active',index - 1);
}
else
{
$("#accordion").accordion('option','active',index);
}
});
});
.accordionStyle{
position: relative !important;
width:500px !important;
margin: 30px auto !important;
}
.accordionStyle h3{
padding-left:35px;
}
p{
font-size:12px
}
.ui-accordion .ui-accordion-icons {
padding-left: 2.2em;
}
.ui-accordion .ui-accordion-header {
display: block;
cursor: pointer;
position: relative;
margin: 2px 0 0 0;
padding: .5em .5em .5em .7em;
min-height: 0;
font-size: 100%;
}
.accordionStyle h3 {
padding-left: 35px;
}
.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr {
border-top-right-radius: 4px;
}
.ui-widget-content {
border: 1px solid #aaaaaa;
background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
color: #222222;
}
<div id="accordion" class="accordionStyle">
<h3>Accordion 1</h3>
<div>
<p>
test1
</p>
</div>
<h3>Accordion 2</h3>
<div>
<p>
test2
</p>
</div>
<link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
Upvotes: 1