Tuesday, November 17, 2009

JQuery slide toggle menu with Cookies, remembering the last state on reload or page navigation

Excited by powerful of JQuery and the numerous numbers of plugins, when I had to do a simple menu, I decided to find a JQuery plugin, I found some on ajaxline.com and on designm.ag, but no one correspond to what I need. A very simple menu, like this:



I tried to make one using just JQuery and Cookie Plugin for JQuery, for remember the last state on reload or page navigation. I found some examples how to use Cookie plugin or how to make a slide toggle with cookies, but no one give me possibility to have more than one slider on a page.

I add in page the code:



This is the CSS:

body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, dl, dt, dd, img, form, fieldset, blockquote
{
margin: 0px;
padding: 0px;
border: 0px;
}
.float-divider
{
clear: both;
display: block;
height: 5px;
font-size: 1px;
line-height: 1px;
}
.menu
{
float: left;
padding: 50px 0 0 50px;
}
.menuTitle
{
float: left;
border: solid 1px #C9D0D8;
background-color: #F1F5F8;
padding: 3px;
cursor: pointer;
width: 150px;
}
.menuImgClose
{
float: left;
background: url('../Images/close_bt.png') right no-repeat;
cursor: pointer;
width: 30px;
height: 25px;
}
.menuIconOpen
{

background: url('../Images/open_bt.png') right no-repeat;
}
.menuContent
{
float: left;
padding: 3px;
}
.menuHeader
{}
All is encapsulated in one div – menu, who position the menu on the page. In my case header of menu consists from 2 divs, the title and the collapse/expand image, you can change it as you want. The content div is required to have the id, to save the state in cookies.

How should work menu. When make click on a header of menu, check the next menu content and if is hide, show it, change the collapse/expand image and save in cookies the state of content div, collapsed or expanded.

This is the code:

$('.menu .menuHeader').click(function() {

var menuContentDiv = $(this).next();
if (menuContentDiv.is(":hidden")) {
menuContentDiv.slideDown("slow");
$(this).children(".menuImgClose").removeClass("menuIconOpen");
$.cookie(menuContentDiv.attr('id'), 'expanded');
}
else {
menuContentDiv.slideUp("slow");
$(this).children(".menuImgClose").addClass("menuIconOpen");
$.cookie(menuContentDiv.attr('id'), 'collapsed');
}
});
And on refreshing or navigation, we get from cookies all the states of the content menu divs, if the state is collapsed; we hide the div and put the right image:
$('.menu .menuContent').each(function() {

var menuContent = $.cookie($(this).attr('id'));
if (menuContent == "collapsed") {
$("#" + $(this).attr('id')).hide();
$("#" + $(this).attr('id')).prev().children(".menuImgClose").addClass("menuIconOpen");
}
});
Now is easy to add a new menu item, just respecting the hierarchy.

Download from RapidShare a VS2008 project.

No comments: