Blog Sections Open

Building a jQuery Accordion Menu That Remembers Its State

A simple accordion menu becomes much easier to use when it remembers which branches were opened and highlights the current page.

This donor started as a practical jQuery menu question, but the pattern is still useful: build a nested accordion, remember opened branches in cookies, and highlight the current link after the page reloads.

The base script

$(document).ready(function() {
    $('ul#accordion ul').each(function(i) {
        if ($.cookie('submenuMark-' + i)) {
            $(this).show().prev().removeClass('collapsed').addClass('expanded');
        } else {
            $(this).hide().prev().removeClass('expanded').addClass('collapsed');
        }
        $(this).prev().addClass('collapsible').click(function() {
            var this_i = $('ul#accordion ul').index($(this).next());
            if ($(this).next().css('display') == 'none') {
                $(this).next().slideDown(200, function () {
                    $(this).prev().removeClass('collapsed').addClass('expanded');
                    cookieSet(this_i);
                });
            } else {
                $(this).next().slideUp(200, function () {
                    $(this).prev().removeClass('expanded').addClass('collapsed');
                    cookieDel(this_i);
                    $(this).find('ul').each(function() {
                        $(this).hide(0, cookieDel($('ul#my-menu ul').index($(this))))
                            .prev().removeClass('expanded').addClass('collapsed');
                    });
                });
            }
            return false;
        });
    });
});

What to improve

If second-level branches all stay open, treat them the same way as the first level: store their state separately and clear descendant cookies when a parent closes.

Current-page highlighting

$(function(){
    $('#accordion a').each(function(){
        if ($(this).attr('href') == window.location.pathname){
            $(this).addClass('current');
        }
    });
});

That small check makes the menu easier to navigate in large trees.

When to use it

This approach still works well for project sidebars, documentation trees, category navigation, and any menu where users revisit the same opened branches.

Newer post

Checking Whether a TV Field Is Empty with IF

When a TV looks filled in direct output but fails inside IF, the usual problem is how the condition is written, not the TV itself.

Older post

RSS Import Options for Evolution CMS Projects

A practical look at RSS import workflows for Evolution CMS and what to check before adopting an older import snippet.