Very new to JQuery, and am struggling to understand .each().
I would like to be able to click on any heading, and have the paragraph under that heading appear, and then disappear. At the moment, I can only get the first paragraph to toggle.
My code is:
<script>
$(document).ready(function(){
$("h2").click(function(){
$("#hidden").each(function(){
$(this).toggle();
});
});
});
</script>
<h2>HEADING 1</h2>
<div id="hidden" style="display:none">
<p>paragraph 1</p>
</div>
<h2>HEADING 2</h2>
<div id="hidden" style="display:none">
<p>paragraph 2</p>
</div>
Thanks very much for any help!
ID of ane element must be unique use class attribute to group similar elements
<h2>HEADING 1</h2>
<div class="hidden" style="display:none">
<p>paragraph 1</p>
</div>
<h2>HEADING 2</h2>
<div class="hidden" style="display:none">
<p>paragraph 2</p>
</div>
then also there is no need to use a each loop, you can call .toggle() in the jQuery wrapper returned by the selector $('.hidden')
$(document).ready(function(){
$("h2").click(function(){
$('.hidden').toggle();
});
});
Update Didn't read the complete question the question seems to be how to toggle the next div
$(document).ready(function(){
$("h2").click(function(){
$('.hidden').hide();
$(this).next().toggle();
});
});
Demo: Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With