Reputation: 2027
I have two divs in my parent class, one of which is found by $(this).parent('div').next('.deal-rolldown').show();
the other, $(this).parent('div').next('.client-rolldown').show();
does not find what appears to by syntactically equal.
In WordPress I iterate an (unknown) number of posts, each has 2 buttons to reveal more content. Up to now I have run a document ready function in each iteration to address each reveal by IDs but this is inefficient.
So I am trying to write a function using classes. Here's the JavaScript
$('.deal-link').click(function() {
$('.deal-rolldown').hide(); // hide all
$('.client-rolldown').hide(); // hide all
if ($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
$(this).next('.deal-rolldown').show();
}
});
$('.client-link').click(function() {
$('.client-rolldown').hide(); // hide all
$('.deal-rolldown').hide(); // hide all
if ($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
$(this).next('.client-rolldown').show();
}
});
Which is operating on this HTML
<div class="company">
<div class="company-inner">
<h2>Company 1 </h2> Company 1 Summary
</div>
<a href="javascript:void(0);" class="deal-link">Deal summary</a>
<a href="javascript:void(0)" class="client-link">Client review</a>
</div>
<div style="display: none;" class="deal-rolldown">
Company 1 reveal 1 content
</div>
<div style="display: none;" class="client-rolldown">
Company 1 reveal 2 content
</div>
<div class="company">
<div class="company-inner">
<h2>Company 2 </h2> Company 2 Summary
</div>
<a href="javascript:void(0);" class="deal-link">Deal summary</a>
<a href="javascript:void(0)" class="client-link">Client review</a>
</div>
<div style="display: none;" class="deal-rolldown">
Company 2 reveal 1 content
</div>
<div style="display: none;" class="client-rolldown">
Company 2 reveal 2 content
</div>
The addClass('active')
works fine so I know I am getting the right button, but the next()
function does nothing. No errors. How can I select the appropriate reveal from each button?
Edit following closure: this is a different question to the one marked as duplicate.
Upvotes: 2
Views: 69
Reputation: 14003
First thing, instead of doing
if ($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
You can use $(this).toggleClass('active');
Your problem is that next()
returns the immediately following sibling, and .deal-rolldown
is not a sibling of your .deal-link
element.
What you want to do is
$(this).parent('div').next('.deal-rolldown').show();
Upvotes: 2
Reputation: 464
The next()
function gets the immediately following sibling that matches the selector. The div with class '.deal-rolldown'
is NOT a sibling of the '.client-link'
or '.deal-link'
links. I would suggest using .closest('.deal-rolldown')
instead of .next()
which will find the closest matching element by traversing up through the current item's ancestors.
Upvotes: 0