Reputation: 74
I am trying to create an accordion inside of an accordion... and I am struggling a little.
essentially, I have a div .applicant
, which upon click adds a class .expand
, which sets the height to auto, but, inside of the .applicant
div, I have another div .applicant-child
, which SHOULD do the same thing, and does... but, .applicant
closes when you click .applicant-child
, meaning you have to click the .applicant
again to open view the nested element.
Here is my code:
HTML
<div class="row">
<div class="col-sm-12">
<div class="applicant">
<p><b>PS4 Tournaments</b></p>
<div class="applicant-child">
<p>lalal</p>
<p>lalal</p>
</div>
</div>
</div>
</div>
jQuery
$('.applicant').click(function(){
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});
$('.applicant-child').click(function(){
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});
I could simply remove $(this).removeClass('expand');
from .appliant
, but we'll be displaying a lot of data, so that isn't ideal.
How do I solve this?
Thanks in advance :)
Upvotes: 0
Views: 200
Reputation: 943
On your click handler if you pass through a param:
$('.applicant').click(function(event){
console.log(event.target);
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});
you can use event.target to check if you are clicking on the parent or the child and decide on what action to take from there.
Upvotes: 0
Reputation: 748
That's just event bubbling an expected behaviour.
See this link on jQuery on how to disable the click-Event
to bubble up the DOM and triggering the event on your parent element.
Basically, you just have to do this:
$('.applicant-child').click(function(event){
event.stopPropagation();
if ($(this).hasClass('expand')) {
$(this).removeClass('expand');
} else {
$( this ).addClass('expand');
}
});
Upvotes: 1
Reputation: 2930
You want to prevent bubbling. Bubbling means, that the event you are reacting to is being passed up the DOM to the parent objects, until it reaches the window.
Check out the "event.stopPropagation()" method, which will prevent any subsequent listeners from reacting.
Upvotes: 0