Jquery toggle accordion

Im trying to make an accordion with toggle which seems to work pretty good now. What i would like to get some help with as a newbie to javascript is the way it is put together.

http://jsfiddle.net/z3wW4/

This isnt pretty i know...

    $(document).ready(function() {
     $('#contact').click(function() {
        $('#content2, #content3').hide(200, 'linear');
          $('#content').toggle(700, 'linear');          
    });
});

$(document).ready(function() {
     $('#services').click(function() {
        $('#content, #content3').hide(200, 'linear');
          $('#content2').toggle(700, 'linear');
    });
});

$(document).ready(function() {
     $('#about').click(function() {
        $('#content, #content2').hide(200, 'linear');
          $('#content3').toggle(700, 'linear');
    });
});

Upvotes: 1

Views: 4205

Answers (3)

red-X
red-X

Reputation: 5128

your code isn't very extensible, you might want to try it like this: http://jsfiddle.net/PzYvA/

$(document).ready(function() {    
    var $menu = $("#menu");
    $menu.children("a").click(function(){
        var $content = $(this).next("div");
        $menu.children("div").not($content).hide(200, 'linear');
        $content.toggle(700, 'linear');
    });
});

also add the following css

#menu > a {
    display:block;
}

and remove the <br /> after the a tags

Upvotes: 1

Beno&#238;t
Beno&#238;t

Reputation: 7427

You can see that your 3 fonctions have quite the same code.
Then, you have to use html class to define the functios of your html element, and then with javascript/jquery, defined how theses fonctions works.

It will simplify your CSS and your javascript:

http://jsfiddle.net/td3UB/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

 $('#menu > a').click(function() { // specifies which a elements
     var that = $(this), // caching the selectors for performance
         divs = $(this).siblings('div'),
         div = $(this).nextAll('div:first');
     divs.not(div).hide(200, 'linear'); // hides all the sibling divs *except* for the
                                        // immediately following div element
     div.toggle(700, 'linear');         // toggles the immediately-following div
});

JS Fiddle demo.

References:

Upvotes: 2

Related Questions