1

I've got a jQuery plug-in to generate accordion-like menus. However, my slideUp() and slideDown() functions seem to be happening simultaneously.

Ideally, I would like all expanded sub-menus to slide up, and then the selected menu item's sub-menu slide down once that's completed. My code is as follows:

jQuery.fn.accordionMenu = function() {
    return this.each(function() {
        $('#menu ul').hide(); // hide all unordered lists
        $('#menu li.selected ul').show(); // drop down selected item's sub-menu
        $('#menu li a').click(function() {
            var speed = 'fast';
            var checkElement = $(this).next();
            if (checkElement.is('ul')) {
                if (!checkElement.is(':visible')) {
                    $('#menu ul:visible').slideUp('slow').parent().removeClass('open');
                    checkElement.slideDown('slow').parent().addClass('open');
                }
                return false;
            }
        });
    });
};

Thanks in advance.

EDIT: Solved with the following:

jQuery.fn.accordionMenu = function() {
    return this.each(function() {
        $('#menu ul').hide(); // hide all unordered lists
        $('#menu li.selected ul').show(); // drop down selected item's sub-menu
        $('#menu li a').click(function() {
            var speed = 'fast';
            var checkElement = $(this).next();
            if (checkElement.is('ul')) {
                if (!checkElement.is(':visible')) {
                    $('#menu ul:visible').slideUp(speed, function() {
                        checkElement.slideDown(speed).parent().addClass('open');
                    }).parent().removeClass('open');
                }
                return false;
            }
        });
    });
};
Martin Bean
  • 38,379
  • 25
  • 128
  • 201

2 Answers2

2

The animations for jQuery can be linked sequentially using the callbacks for the functions. So for example

$("#menu").slideUp("fast", function () {
    $("#menu2").slideUp("fast", function () {
        $("#menu3").slideDown("slow");
    });
});

This little snippet will roll up #menu, then roll up #menu2, and finally roll down #menu3

Check the documentation for some examples: http://api.jquery.com/slideUp/

Also, this question might be of use: jQuery animation queues across multiple elements

Community
  • 1
  • 1
Andrew Burgess
  • 5,300
  • 5
  • 30
  • 37
1

I'd do this using dynamic classes on the elements to flag them as being expanded or collapsed. So, for example.

$("#menu ul").click( function() {  
  $("#expanded").slideUp( function() {
    $("#expanded").removeClass("expanded");
    $this.slideDown();
    $this.addClass("expanded");
  });
});

that probably won't work verbatim as I've not tested it, but it shows the principle.

Hill79
  • 11
  • 1
  • Thanks. I'm actually using a dynamic class of "open", so I may further improve my plug-in above to utilize that approach. Thanks! – Martin Bean Aug 21 '10 at 16:47