user2421594
user2421594

Reputation: 81

Toggle when clicking child element and not parent

What I want to do is when you click on the actual anchor tag...I want the div below to slide...The only way it slides toggle is if I change the click function target to be the ".flip" class and not on the ".flip a"

// and Here is the JS
// Slide panels

$('.flip a').click(function(e) {
  $(this).next('div.panel').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="flip">
  <h4>Example</h4>
  <a href="">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

<div class="flip">
  <h4>Example</h4>
  <a href="">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

Upvotes: 1

Views: 750

Answers (2)

RobertoNovelo
RobertoNovelo

Reputation: 3810

As said in the other answer, next tries to find a same level element with the selectors provided, so you could use .parent().next(). Also, your href is taking you somewhere else when clicking on .flip a.

$('.flip a').click(function(e) {
  $(this).parent().next('.panel').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="flip">
  <h4>Example</h4>
  <a href="#">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

<div class="flip">
  <h4>Example</h4>
  <a href="#">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

.next() looks for siblings, which .panel isn't. You need to move up to the parent .flip element first.

$(this).closest('.flip').next('div.panel').slideToggle();

https://api.jquery.com/category/traversing/tree-traversal/

(You'll probably want to cancel the default click with e.preventDefault() as well.)

$('.flip a').click(function(e) {
  e.preventDefault(); // cancel the default click
  $(this).closest('.flip').next('div.panel').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="flip">
  <h4>Example</h4>
  <a href="">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

<div class="flip">
  <h4>Example</h4>
  <a href="">Link Button</a>
</div>
<div class="panel" style="display: none;">
  <p>Example Panel</p>
</div>
<!--End panel-->

Upvotes: 1

Related Questions