I have some collapsible divs, where when clicking on the title they open or close. The problem is that clicking on one of them, opens all the others as well, and the same happens when closing them. Here the code:
$(document).on("click", ".toggle-title", function(evt) {
$(this).parent().find('.toggle-content').slideToggle(600);
$(this).find('i').toggleClass('rotate-toggle');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="toggle-title">
<p class="title_celeste">EN TRÁNSITO <i class="fa fa-angle-down font18"></i></p>
</a>
<div class="toggle-content">
CONTENIDO
</div>
<a class="toggle-title">
<p class="title_celeste">PORTERÍA <i class="fa fa-angle-down font18"></i></p>
</a>
<div class="toggle-content">
CONTENIDO
</div>
<a class="toggle-title">
<p class="title_celeste">CALADO <i class="fa fa-angle-down font18"></i></p>
</a>
<div class="toggle-content">
CONTENIDO
</div>
My question is: Is there a way to click open a single div at a time without having to add a particular class for each div?
Check for .active
class and reduce your html
portion.
Implement slideDown()
and slideUp()
, depending on the state of the title.
If you really need to use <a>
tags, consider moving them inside of your <p>
tags, as mentioned in the comments above.
$('.title_celeste').on("click", function(evt) {
evt.preventDefault();
let _this = $(this),
ct = _this.next('.toggle-content');
// check if clicked title has active class
if(_this.hasClass('active')){
_this.removeClass('active');
ct.slideUp();
} else {
$('.title_celeste.active').removeClass('active');
$('.toggle-content').slideUp();
_this.addClass('active');
ct.slideDown();
}
});
.toggle-content {
display: none;
padding: 2rem 1rem;
background: #f1f1f1;
}
.title_celeste {
background: #111;
color: #fff;
padding: 1rem;
cursor: pointer;
margin: 0;
}
.title_celeste.active {
background: red;
}
.title_celeste:not(.active):hover {
background: green;
}
.title_celeste i {
transition: transform .3s ease;
float: right;
}
.title_celeste.active i {
transform: rotate(-180deg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<p class="title_celeste">EN TRÁNSITO <i class="fa fa-angle-down font18"></i></p>
<div class="toggle-content">
CONTENIDO
</div>
<p class="title_celeste">PORTERÍA <i class="fa fa-angle-down font18"></i></p>
<div class="toggle-content">
CONTENIDO
</div>
<p class="title_celeste">CALADO <i class="fa fa-angle-down font18"></i></p>
<div class="toggle-content">
CONTENIDO
</div>