Jump to content

multiple toggle effect


Jaswinder

Recommended Posts

Hello everyone.. I am using a toggle effect on divs, what i want is a single code for all divs .. right now i have to write the code multiple times i.e for every div individually . I know it can be achieved by $(this) , but i dont know how, as  i am new to jquery.

 

here is my code and its working fine,

<div class="tricks_head">First</div>
<div id="trick1"></div>

<div class="tricks_head2">second</div>
<div id="trick2"></div>

<div class="tricks_head3">third</div>
<div id="trick3"></div>

<script type="text/javascript">

$( ".tricks_head" ).click(function() {
$( "#trick1" ).toggle('slow');
});
$( ".tricks_head2" ).click(function() {
$( "#trick2" ).toggle('slow');
});
$( ".tricks_head3" ).click(function() {
$( "#trick3" ).toggle('slow');
});

</div>

In my project i have  50 div , so can't write it 50 times.. so any help please ?

Link to comment
https://forums.phpfreaks.com/topic/287893-multiple-toggle-effect/
Share on other sites

Do you have control of the HTML mark-up? If so, you could try something like this:

<div class="tricks_head">
    <div class="trick">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, totam.
    </div>
</div>

<div class="tricks_head">
    <div class="trick">
        Ratione, maiores labore nulla atque recusandae repellendus est. Iusto, ut.
    </div>
</div>

With non-numeric classes for the divs, the JavaScript is fairly simple:

$('.tricks_head').click(function() {

    var $tricks_head = $(this);

    $tricks_head.find('.trick').toggle('slow');

});

You can see a working demo here: http://jsfiddle.net/codebyren/AqSp2/

 

If the divs are siblings in the HTML then you can use the next() or nextall() method - something like this:

$('.tricks_head').click(function() {

    var $tricks_head = $(this);

    $tricks_head.next('.trick').toggle('slow');

});

Updated demo here: http://jsfiddle.net/codebyren/AqSp2/1/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.