Jump to content
Jaswinder

multiple toggle effect

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 ?

Share this post


Link to post
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/

 

Edited by behicthebuilder

Share this post


Link to post
Share on other sites

thanks for reply

 

you have enclosed the trick class inside the  tricks_head class,

 

but i need them both seprate, like this

 

<div class="tricks_head">First</div>
<div class="trick"></div>

 

Is it possible or any other alternative ?

Edited by Jaswinder

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.