A jQuery slider on cookies

So you want to know huh? Very nice of you! I’ll cover the script step by step, explaining everything.

$(document).ready(function() {
});

You should know this: this is the started jQuery way of saying “execute the following script when the document is ready to execute scripts”.

var panel = $("#box");
var button = $("#top a");
var initialState = "expanded"; // "expanded" OR "collapsed"
var activeClass = "hidden";
var visibleText = "hide";
var hiddenText = "show";

Our configuration. I’m simply storing everything in variables so we don’t have to hardcode them in the script. Panel is the div we’ll be hiding/showing, button is the item that’ll close it. Note that this doesn’t have to be a link. You can take anything you want really. initialState is how we want to box to start off: expanded or hidden. Change this to collapsed if you want the first click on button to show the panel, rather than hide it.

Moving on: activeClass is the class that’ll be added to button when panel is hidden, thus allowing further styling. And last but not least there are two more variables if you want the text of button to change. If you don’t want text in your button, you could leave them emtpy, you could hide the text with CSS etc…

if($.cookie("panelState") == undefined) {
	$.cookie("panelState", initialState);
}

Our script works with cookies. It even needs one to start off, so here we check if the cookie is allready set. If not, it adds one with the value you entered at initialState.

var state = $.cookie("panelState");

Simply get the value from the cookie into a variable. This isn’t really necessary, but I just consider it better coding practice.

if(state == "collapsed") {
	panel.hide();
	button.text(hiddenText);
	button.addClass(activeClass);
}

Wether it’s the first time you execute the script or it’s on a page reload, the panelState cookie is set and the script knows if you want panel to be collapsed or expanded. The script assumes you want panel to be expanded, but if the cookie tells it to collapse it, it does it here. It also adds the correct text and class to button.

button.click(function(){
	if($.cookie("panelState") == "expanded") {
		$.cookie("panelState", "collapsed");
		button.text(hiddenText);
		button.addClass(activeClass);
	} else {
		$.cookie("panelState", "expanded");
		button.text(visibleText);
		button.removeClass(activeClass);
	}
	panel.slideToggle("slow");
	return false;
});

The actual clicking magic. When you click button the script asks for the current state, stored in the panelState cookie. If that equals “expanded”, the cookie is changed to collapsed, the button text changes and the class is added because we will be hiding panel now. If it’s not “expanded” (else) it can only be one other thing: collapsed. So we set the cookie to expanded, change the button text and remove the class.

Finally we slideToggle panel. This part actually doesn’t care if it’s expanded or collapsed. jQuery will check that for us and show the panel when it’s hidden or the other way around. The last line simply prevents our browser from actually following the button link, thus preventing the # to be added to our url, keeping everything clean!

That’s all there is to it. I hope you can use the script or that you at least learned something from this. The cookie plugin is one handy thing and lots of it could be achieved with it!

One final note: I’m more a PHP developer than a javascripter. It could very well be there are some flaws in this script and if you think you know something better, if you know of some trick that could make this script better, please let me know!

If you’re concerned about users who won’t have JavaScript turned on, go read the addition!

Bookmark:
  • Digg
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Reddit
  • TwitThis
  • Facebook
  • E-mail this story to a friend!

Pages: 1 2

33 people left their say »

  • That’s pretty useful man!

    I was wondering if there’s a trick to it vice versa?

    Like if you have a long list of names and you want to view the rest of it by clicking “more…”.

  • Sure, just put the “more…” in a div, set up the slider but change initialState into collapsed!

  • Cheers man. I will keep that in mind as I will need it in an upcoming site I’m working on.

  • Thanks for the credit, and hey, if this works better for you, more power to you. I am just concerned though about the link for “hide” if JS is disabled it does not function? Maybe if you created the link with jQuery as well, and added it in, then it would be more accessible.

  • [...] few days ago I posted a script that allowed you to create a jQuery slideToggle that would remember it’s last state throughout page reloads. The original idea came from Matt [...]

  • Im a bit of a newb to JQuery but I think a different approach would also work for Sir Ali.
    The main drawback that I see is separating your content with multiple DIVs for the “more” content. Perhaps if your name container height was static and your list was not very long and of course not dynamically loaded.
    I can see a real hassle in loading a table of information in PHP and then writing another table in a second div. As a PHP coder more so I would look for a solution there.
    What I would suggest doing is create a div with a preset height and simply use the Animate method with a expanded height and overflow:hidden the rest. The height could be dynamic as well you could place a inner wrapper DIV and pull its height attribute from the DOM.(NOTE: I think simply using 100% would also work)
    Then put another DIV below with your anchor that activates the code, use the same switching method used here and blam!
    The first div would be set at whatever height you want, with the content inside that goes beyond that(its overflow) hidden. Once you click the anchor, the height is “animated”. JQuery treats animate the same and would revert to the other height within the same command just like toggle.

    Just my .02

  • Great Work!! it s a pretty cool script.
    I noticed that it runs well on FF, but doesnt seem to run on IE6?
    Do you what need to be changed or modified to make it run on IE6?
    Thanks

  • This is great work! Works great in FF and IE7.

    Im also having some issues in IE6. Will you be releasing a fix for it?

    Thanks

  • I think the IE6 problem could be related to jquery cookies, I’ve been trying to get around it this morning but no luck yet!

    God damn you IE6.

    http://www.porcelaindev.co.uk

  • I’m testing this on a basic level to hide a nagivation div. Unfortunately it seems to load all content on the page before addressing the show/hide.

    This means that if i click “Hide” it works, but when i refresh the page, that hidden content shows until the document finishes loading.

    Ideas? Thanks a lot!

    • That is the downside of working with JavaScript only: the jQuery code only starts when the document is loaded. You could try using the code outside the $(document) function, but I don’t know how well that would work.

      What I would do is hardcode this serverside: Check the cookie in php (that should be possible, i think) and then echo ‘style=”display:none”‘ in your navigation ul, div, whatever to hide it on page load.

  • Great work!

    I have a question. How can i change the show/hide text for image link or source?

    Thanks a lot!

  • Yes I want change show and hide text to image. I try change and doesn’t work:

    // the text of the button when the panel’s expanded
    var visibleText = “image/show.png”;
    // the text of the button when the panel’s collapsed
    var hiddenText = “image/hide.png”;

  • BzS, to that change button.text to button.html

    In the variable at the top add your HTML.

  • Hello, thank you for the script.

    Could someone advise how to make the cookie remember site-wide and not by folder? I tried adding path to the first bit to:

    $.cookie(“panelState”, initialState, { path: “/” });

    but it does not solve. Thanks!

  • I applied ‘/’ path to each case when cookie is set. This seems to fix :)

    —————————————
    if($.cookie(“panelState”) == undefined) {
    $.cookie(“panelState”, initialState, { path: ‘/’ });
    }

    var state = $.cookie(“panelState”);

    if(state == “collapsed”) {
    panel.hide();
    button.html(hiddenText);
    button.addClass(activeClass);
    }

    button.click(function(){
    if($.cookie(“panelState”) == “expanded”) {
    $.cookie(“panelState”, “collapsed”, { path: ‘/’ });
    button.html(hiddenText);
    button.addClass(activeClass);
    } else {
    $.cookie(“panelState”, “expanded”, { path: ‘/’ });
    button.html(visibleText);
    button.removeClass(activeClass);
    }

    panel.slideToggle(“slow”);

    return false;
    });
    —————————————

  • Great script. :D
    A question though, is it possible to make it horizontally-scaled? So it collapses/expands horizontally, not vertically.

  • sweet! nice job, thanks for sharing!

  • Helped me a lot, thanks!!!

  • Super thanks for this tutorial, I implemented it on a popular news website. You are the best!

  • Super cool, works perfectly!
    thanks :)

  • Hi All,
    I have multiple slide boxes on a single page. So I need to take this code a couple of steps further. This is my first attempt to play with jquery code.

    Im guessing I need to find out how to know what button was clicked on and make the changes accordingly. Im not sure how to tell what was clicked on…….

    I so want to save the changes in my database by a Ajax call. But that turns out to be the easy part…

    thanks,

    Scott.

  • There is an error in your code that keeps the script from working. On line 30 you will see a “<" (without quotes). It took me about an hour to figure out why the script wasn't working. But that little booger was in there.

    Thanks for the script!

  • Hey, thank’s a lot for this, i need help, i need to have multiple boxes in a page, but opening only the one clicked, im using classes, i know a solution that works for me, but no cookies :(

    This one works, but it has no cookies http://www.sohtanaka.com/web-design/examples/toggle/

    Thank you

  • GREAT SCRIPT !!

    Had issues with multiple divs and this one not covering them and just made the z index higher.
    So if anyone has issues like this where the div does not cover your text then the thing i did to fix was to add to the style z-index: 20000; you can make the 20000 anything you want i just wanted to make sure it was on top :D

  • Nice script !

    But how do i change the Hide and Show text into a image ?

    I try a couple things but it did not work.
    So i hope someone here can help me out.

  • Hi and Great work, works a charm too.

    I just wanted to ask if it was possible to expand and fade in or out?

    Cheers,
    Tony

  • I would love to know how to have the panel open and close the first time a visit comes to my site, to make them aware of the panel. Is this possible using your existing code?

    Thanks again for a great tutorial.

    • This code is really outdated, but the idea is still the same. If you want to open/close the panel upon the first visit, you could check for the existence of a second cookie (visited = false/true or something like that), if it isn’t present, open/close the panel and then set that specific cookie.

Have your say »