jimbouton
jimbouton

Reputation: 259

Jquery accordion

I am attempting to make a simple accordion where the user clicks on level 1 to see level 2, clicks on level two to see level three and so on. Level 1 will be duplicated many times so i am using the .children method to avoid all the levels 2's opening when level 1 is clicked.

The problem is when level 2 is clicked it opens level 3 but also closes level 1. I could target each directly to solve this issue but i want to do it with the minimum amount of code. Any suggestions would be much appreciated.

<div class="level1">
Level 1
    <div class="level2">
    Level 2
        <div class="level3">
        Level 3
        </div>
    </div>
</div>

<script type="text/javascript">

$(document).ready(function(){
    $('.level1').click(function(){
        $(this).children('.level2').slideToggle('300');
        }); 
});
</script>

Upvotes: 0

Views: 115

Answers (3)

mesimplybj
mesimplybj

Reputation: 639

You can give each division a common propert to excess like class

<div class="level" id="level1">
    Level 1
    <div class="level"  id="level2" >
    Level 2
        <div class="level"  id="level3" >
        Level 3
    </div>
</div>

then you can toggle them as

$('.level').click(function() {
    $(this).children('div').slideToggle('300');
    event.stopPropagation();
});

after each click you stop executing the event again
I think this will help you
here is the example http://jsfiddle.net/Simplybj/aZ5wv/

Upvotes: 0

Manse
Manse

Reputation: 38147

Try this :

$(document).ready(function(){
    $('div').click(function(event){
      $(this).find(">:first-child").slideToggle('300');
        event.stopPropagation();
    }); 
});​

This only opens the first child - example here. You need the event.stopPropagation to stop the event bubbling up the DOM tree and causing unexpected toggles !

Upvotes: 0

PeeHaa
PeeHaa

Reputation: 72709

You can make that more generic (so you can easily add more levels later like):

<div class="level1 acc">
Level 1
    <div class="level2 acc">
    Level 2
        <div class="level3 acc">
        Level 3
        </div>
    </div>
</div>

(function($) {
    $('.acc').click(function(){
        $(this).children('div').slideToggle('300');

        return false; // this prevents event bubbling (thus preventing the behavior you have now) 
    }); 
})(jQuery);

Demo: http://jsfiddle.net/PeeHaa/7gAzx/

Upvotes: 2

Related Questions