Hey everyone, I'm just starting to learn how to code and still getting the hang of using Stack Overflow so please bear with me if my question isn't perfectly formatted. I have created an accordion that is almost functioning correctly, but I need a bit of help tweaking it. Currently, my accordion has two tabs and when one tab is opened, the other one closes which is working fine. However, I want to make sure that at least one tab is always open, specifically the first one when the page loads. So, if I click on the second tab, the first one should remain open until I explicitly close it by clicking on it again. Right now, both tabs are collapsed on page load and can be closed even if they are already open.
$(document).ready(function() {
function close_accordion_section() {
$('.accordion .accordion-section-title').removeClass('active');
$('.accordion .accordion-section-content').slideUp(300).removeClass('open');
}
$('.accordion-section-title').click(function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.active')) {
close_accordion_section();
} else {
close_accordion_section();
$(this).addClass('active');
$('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
}
e.preventDefault();
});
});
.accordion,
.accordion * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.accordion {
overflow: hidden;
border-radius: 5px;
background: white;
}
.accordion-section-title {
width: 100%;
padding: 0px;
display: inline-block;
background: #585858;
transition: all linear 0.15s;
font-size: 14px;
color: #F2F2F2;
}
.accordion-section-title.active,
.accordion-section-title:hover {
background: white;
text-decoration: none;
font-weight: bold;
color: #585858;
}
.accordion-section:last-child .accordion-section-title {
border-bottom: none;
}
.accordion-section-content {
padding: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion">
<div class="accordion-section">
<a class="accordion-section-title" href="#accordion-1">Accordion Section #1</a>
<div id="accordion-1" class="accordion-section-content">
<p>accordion 1 text</p>
</div>
</div>
</div>
<div class="accordion">
<div class="accordion-section">
<a class="accordion-section-title" href="#accordion-2">Accordion Section #2</a>
<div id="accordion-2" class="accordion-section-content">
<p>accordion 2 text</p>
</div>
</div>
</div>
Any help would be greatly appreciated. Thank you!