I use slideToggle for a simple accordion, but when clicked on the opened accordion to close, it closes and than jumps back to opened.
HTML
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
JAVASCRIPT
$('.footer-menu').hide();
$('.footer-title').click(function(){
$('.footer-menu').slideUp();
$(this).next('.footer-menu').slideToggle();
});
Demo: CodePen
CodePudding user response:
You can check if the next element where the click event has occurred is visible or not depending on this move $('.footer-menu').slideUp();
line inside if condition.
Demo Code:
$('.footer-menu').hide();
$('.footer-title').click(function() {
var isOpen = $(this).next('.footer-menu').is(":visible"); //check if the next elemnt is visible (means we are closing it)
if (!isOpen) {
$('.footer-menu').slideUp();
}
$(this).next('.footer-menu').slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
<div>
<h2 >First title</h2>
<ul >
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>