Single jQuery function to toggle multiple elements individually
html, jquery
Solution
Use same class for all sets with event source. You can use only two classes for n number of html sets quite effectively.
Live Demo
<div class="first">Toggle first</div>
<p class="first-p">First hidden paragraph.</p>
<div class="first">Toggle second</div>
<p class="first-p">Second hidden paragraph.</p>
Use current object with next()
$('.first-p').hide();
$( "div.first" ).click(function() {
$(this).next().slideToggle(1000);
});
Problem
I need a single jQuery function that can be re-used to toggle multiple elements individually. The code example on the jQuery page at http://api.jquery.com/slidetoggle/ works well for a single element using a button but not for multiple elements using non-button elements. My code (adapted from the jQuery slidetoggle example): ``` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>slideToggle demo</title> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> </head> <body> <div class="first">Toggle first</div> <p class="first">First hidden paragraph.</p> <div class="second">Toggle second</div> <p class="second">Second hidden paragraph.</p> <script> $( "div.first" ).click(function() { $( "p.first" ).slideToggle(0); }); </script> <script> $( "div.second" ).click(function() { $( "p.second" ).slideToggle(0); }); </script> </body> </html> ``` The code allows each element to be toggled individually which is what I want. However, there are two problems with my code: It is repetitive and inefficient in that a new script needs to be written for each element that I wish to make toggleable (I would prefer a single function that would toggle any element of a particular class name). By default, the page is displayed with all elements displaying in full. I would prefer to have the toggleable elements hidden by default. I have been unable to find a straightforward solution which addresses both issues. Any help would be appreciated.