Create a jQuery Accordion – remain open after page load

Written on Monday, March 30th, 2009 at 3:28 pm and is filed under Blog, jQuery.

I am currently working on this site for a client: http://www.hornedpout.com/ – a very basic portfolio website for a designer/writer. I didn’t want to use the bulky code of the jQuery UI so I decided to use the smaller version, below:

$(".menu-header").click(function() {
        $(this).next().toggle('slow');
        return false;
}).next().hide();

The HTML would look something similar to:





That code will use jQuery’s toggle() function. When the user clicks the h2 tag it will close all elements until the next
tag. This snippet is very handy for creating a quick accordion effect, this can also be found on the jQuery’s documentation

Now we have the guts sorted out, but the problem is if you travel to another page within that category, it will close. I’m sure you want to check out the code that is going to do this.

Keep that open!

var matches;
     if( matches = (new String(document.location)).match(/?c=w+/) ) {
        $("a[href=" + matches[0] + "]").parents("ul").toggle();
     }

The code above is fairly straight forward. The first line checks to see if we already have a sub-menu open. It evaluates by looking at the current pages URL “?c=page_here”.

The latter part of the code. Now that we grabbed the current URL of the sub-menu, we can use this to find the parent menu which is the
ul and display it:

$("a[href=" + matches[0] + "]").parents("ul").toggle();

The quick fix to keep your accordion block open while traveling to different URLS. To achieve the URLS of “?c=page”. I am using this PHP code below save it as index.php, also create a header.php and a footer.php.

Give it a shot, hope that this can work for you, it did wonders for my project. Also thanks to Kent, for helping me. If it did work post some examples!

Spread the ♥

  • Digg
  • del.icio.us
  • Facebook
  • NewsVine
  • Mixx
  • Google Bookmarks
  • email
  • Reddit
  • Design Float
  • StumbleUpon
  • Technorati

other related posts...

  1. How to load data using JSON/PHP using jQuery
  2. Combining Selectables And Draggables Using jQuery UI
  3. Working with the jQuery live function
  4. Another jQuery UI Slider Example
  5. Two Panel Slick Drop Down Using jQuery

Take a peak at some more?

Leave a Reply