Reputation: 1576
I've this code :
$('.close-button').click(function() {
$(this).closest('#hidden').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bloc">
<h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
<div id="hidden">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
</div>
</div>
<div class="bloc">
<h2>Click on that link to display the content <a href="#" "close-button">Click here</a></h2>
<div id="hidden">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
</div>
</div>
When you click on the link, the div #hidden
is displayed.
I try to do this in Jquery but it does not work.
Thanks for your help !
Upvotes: 2
Views: 44
Reputation: 15154
Dont use duplicate id
, instead use a class
.
.closest
only looks up through the parents, and not of the siblings to those parents.
$('.close-button').click(function() {
$(this).parent().next().slideToggle();
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bloc">
<h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
<div class="hidden">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
</div>
</div>
<div class="bloc">
<h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
<div class="hidden">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
</div>
</div>
Upvotes: 1
Reputation: 85545
First grab the parent element and then get the next element to it:
$('.close-button').click(function() {
$(this).parent().next().slideToggle();
});
To note: the closest method gets the element's closest parent element.
Upvotes: 1