Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single jQuery function to toggle multiple elements individually

Tags:

html

jquery

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:

  1. 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).

  2. 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.

like image 758
Grant_Bailey Avatar asked Sep 30 '22 09:09

Grant_Bailey


1 Answers

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);
});
like image 181
Adil Avatar answered Oct 10 '22 02:10

Adil