Unobtrusive jQuery slide toggle with cookies

August 26th, 2008

Using jQuery to create a “slide/hide” toggle and remembering the last state on reload, or page navigation

Recently at work I was assigned to come up with a “framework” of sorts for developing sites within our intranet. I thought it would be nice to add some flare to the design, enter jQuery. On all our intranet sites we have a standard header with some navigation that does not always look the best on all designs, so I needed a way to hide this, but be able to show it when a user needed one of these links.

I found some solutions, but I wanted to take it one step further by making this piece of the site unobtrusive, which is something you should always strive for when dealing with behavior (JavaScript). I then found a need to remember the last state of the toggle. This is not always a requirement, depending on the data being toggled you may not have a need for this, but alas, I did.

Here is what you need to get going:

For the impatient folks out there now might be a good time to:

Next, you are going to need to have some initial markup to work with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="Content-Style-Type" content="text/css" /><title>ifoh designs: jquery slider test</title><link rel="stylesheet" href="/css/jquery-slider.css" type="text/css" media="screen" /><script type="text/javascript" src="/scripts/jquery.js"></script><script type="text/javascript" src="/scripts/jquery-cookie.js"></script>

<script type="text/javascript" src="/scripts/jquery-slider.js"></script>

</head>

<body>

<div id="panel">

<h3>The most important content</h3>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean id

turpis at elit convallis varius. Nunc et purus. Nulla consectetuer

aliquam metus. Nulla facilisi. Nulla facilisi. In euismod libero in

nulla. Vivamus suscipit mi a odio. Proin laoreet imperdiet augue.

Phasellus id eros. Praesent vestibulum, quam nec condimentum mollis,

ante eros fermentum augue, non consectetuer diam odio et nulla. Proin

vel mi sed odio aliquam hendrerit. Quisque accumsan varius lacus. Fusce

eget arcu vitae nunc pellentesque ultricies. Lorem ipsum dolor sit

amet, consectetuer adipiscing elit. Aenean est nisi, dictum non, tempor

eget, convallis eget, nulla.</p>

</div>

<div id="wrapper">

<h1>Jquery Slider Test - Home Page</h1>

<ul>

<li class="selected"><a href="jquery-slider.html" title="Home page">Home</a></li>

<li><a href="jquery-slider-2.html" title="jquery-slider page 2">Page 2</a></li>

<li><a href="jquery-slider-3.html" title="jquery-slider page 3">Page 3</a></li>

</ul>

<div id="content">

<h2>Home Page Stuff</h2>

<p>some supporting content</p>

</div> <!-- END #content -->

</div> <!-- END #wrapper -->

</body>

</html>

Let’s take a look at what makes up the slider script:

// Author:              Matt Rossi

// Website:             ifohdesigns.com

// Article Source:      http://ifohdesigns.com/blog/tutorials/

// Last Modified:       August 27, 2008// IF YOU WISH TO USE THIS SCRIPT I WOULD APPRECIATE A BACKLINK

$(document).ready(function() {

$("#panel").hide();

var a = $("<a>toggle header</a>").attr('href','#').addClass("btn-slide");

 $('#wrapper').before(a);

$(".btn-slide").click(function(){

if ($("#panel").is(":hidden")) {

        $("#panel").slideDown("slow");

 $(this).addClass("active");

         $.cookie('showTop', 'collapsed');

 return false;

} else {

        $("#panel").slideUp("slow");

 $(this).removeClass("active");

        $.cookie('showTop', 'expanded');

 return false;

}

});

// COOKIES

    // Header State

    var showTop = $.cookie('showTop');

// Set the user's selection for the Header State

    if (showTop == 'collapsed') {

 $("#panel").show();

 $(".btn-slide").addClass("active");

};

});

In plain English what is happening here is essentially…

  1. hide the div with the content we want “slideable”
  2. create an anchor, give it a class and insert it into the page
  3. when you click the newly created button either show or hide the content area
  4. record the state of the toggle
  5. set the cookies based on the state of the toggle
  6. show or hide the content area based upon the cookie

We also add an “active” class to the anchor to give it the green color when we are able to see the #panel area.

If JS is disabled the user should see the contents of #panel by default before any other content.

Take a look at the finished product now!

By all means, I am in no way an expert with jQuery, so if you notice a bug, just let me know. If you have a better solution, I would love to see/hear it, so share with us all! If you do wish to use this script, I would appreciate a backlink, thanks.

Related posts in tutorials

Subscribe to our RSS Feed!

43 Responses to “Unobtrusive jQuery slide toggle with cookies”

Leave yours now...

  1. #1 Graphic Design Links and Tutorials says...

    Unobtrusive jQuery slide toggle with cookies | ifoh designs

    Want an unobtrusive solution to a slide toggle div using jQuery? Look no further!

    • Posted on August 26th, 2008 at 4:00 pm
  2. #2 Illusiv says...

    Really like the idea and gonna need this. Is it possible to get more then one slider on a page?

    • Posted on August 27th, 2008 at 3:36 am
  3. #3 CHelmertz says...

    You might want to add a “return false;” after if/else of the call, preventing the browser to follow the link to “#” (thereby messing with back-button).

    • Posted on August 27th, 2008 at 6:09 am
  4. #4 Matt says...

    @ Illusiv - I will have to rework the script for that since I am using an ID for this. I will work on it, check back.

    CHelmertz, definitely a great point, I missed that, and thank you for pointing that out. I will update the code, thanks again!

    • Posted on August 27th, 2008 at 9:40 am
  5. #5 Unobtrusive jQuery slide toggle with cookies | CrazyLeaf Design Blog says...

    […] an unobtrusive solution to a slide toggle div using jQuery? Look no further! View source Posted in : General Post statistics : 1 […]

    • Posted on August 27th, 2008 at 5:50 pm
  6. #6 What Are the Best Sources of Design Community News? | Vandelay Website Design says...

    […] Unobtrusive jQuery Slide Toggle with Cookies […]

    • Posted on August 27th, 2008 at 7:44 pm
  7. #7 Bram says...

    I’m reworking my site and wanted to have a toggle for my “latest project” box. I came across this and found it very nice. However, it didn’t work for me and I found it very unhandy, in that you need to use the correct html markup.

    That’s why I decided to rework your idea. What I came up with is completely different code, but works just as well.

    If you’re interested:
    [source:js]
    $(document).ready(function() {

    var panel = $(”#latest_project”);
    var button = $(”#latest_top a”);
    var initialState = “expanded”; // “expanded” OR “collapsed”
    var activeClass = “hidden”;
    var visibleText = “^ hide”;
    var hiddenText = “v show”;

    // don’t edit below this line
    //—————————

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

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

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

    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;
    });
    });
    [/source]

    • Posted on August 28th, 2008 at 2:08 pm
  8. #8 Help Developer - Graphic and Web Design Blog with Collections, Freebies, Tutorials and Forums » Blog Archive » HD Todaily - 28/08/08 says...

    […] If you fancy learning Ruby on Rails then check out the first edition of a series from NetTuts on learning Ruby on Rails from scratch and if you like jQuery then check out how to create an Unobtrusive jQuery slide toggle with cookies. […]

    • Posted on August 28th, 2008 at 3:33 pm
  9. #9 Matt says...

    @ Bram
    I appreciate your effort, but if this is the script that is on your site, it does not degrade with JS turned off, which was one of the main features of the script I wrote.

    Try it yourself: turn JS off and you will still see this button that tells you to “^ hide” something, that does not do anything when you click it.

    • Posted on August 28th, 2008 at 7:39 pm
  10. #10 Websites You Shouldn´’t Have Missed in August says...

    […] - Unobtrusive jQuery slide toggle with cookies […]

    • Posted on August 31st, 2008 at 4:09 pm
  11. #11 jQuery Slide Toggle with Cookie by Chad Coleman says...

    […] is a very handy write up and a demo page of how to create a slide toggle effect. The handiest part is the cookie it sets to […]

    • Posted on September 9th, 2008 at 1:29 pm
  12. #12 Vegard says...

    Thanks for writing this down, I adapted it for my site (and a new theme for the ATutor LCMS), and wrote down how to make it work if you’re looking for a togglable *side menu*, and where the initial state is to show the menu, not hide it!

    http://atutor.no/2008/09/create-side-menu-toggle-function-cookies-jquery

    cheers, Vegard

    • Posted on September 16th, 2008 at 8:06 am
  13. #13 Matt says...

    Hey Vegard, that is great. Glad I could be of some assistance, thanks for stopping by!

    • Posted on September 16th, 2008 at 9:12 am
  14. #14 Ryan says...

    Sweet mate, thanks for sharing.

    Anyone know how to get this to do multiple div’s?
    Pleeeease? =)

    • Posted on September 22nd, 2008 at 2:41 am
  15. #15 Eugene says...

    I am looking for some idea and stumble upon your posting :) decide to wish you Thanks. Eugene

    • Posted on October 21st, 2008 at 1:32 pm
  16. #16 Adam says...

    Absolutely perfect… Thanks for sharing!

    • Posted on November 1st, 2008 at 1:16 pm
  17. #17 bay-community.com redesigned says...

    […] thing I figured out was the “Quick Links” at the top. It’s a jQuery slide toggle. […]

    • Posted on November 14th, 2008 at 5:03 pm
  18. #18 Top 50 plugins gratuitos e tutoriais para jQuery - Blog do yogodoshi says...

    […] Jquery Slider Crie facilmente aquele efeito do conteúdo sendo deslizado ao clicar em algum link. […]

    • Posted on November 23rd, 2008 at 12:57 pm
  19. #19 sam says...

    one more request for multiple div !!
    thanks!!

    • Posted on December 19th, 2008 at 3:38 pm
  20. #20 Jason Maletsky says...

    Thanks for the awesome plugin. Saved me for a large AJAX site I’m working on.

    • Posted on January 4th, 2009 at 2:19 pm
  21. #21 Joe says...

    Im having an issue with the Div flickering on as the page loads, then hides. Anyone else have this happen to them?

    • Posted on January 9th, 2009 at 6:27 pm
  22. #22 Daniel says...

    This doesn’t work when you’re working with Search Engine-Friendly URLs (subdirectories), only works with files inside the same “folder”.

    • Posted on January 11th, 2009 at 8:25 am
  23. #23 My web notables… | Folks Pants: Tailor Made Internet says...

    […] Unobtrusive jQuery slide toggle with cookies | ifoh designs Unobtrusive jQuery slide toggle with cookies | ifoh designs […]

    • Posted on January 17th, 2009 at 4:04 am
  24. #24 Bobby says...

    I see how to position the “Toggle Header” link. How come you can only put the link before or after a div and not actually IN a div?

    Any help please.

    • Posted on February 16th, 2009 at 3:38 pm
  25. #25 Bobby says...

    Also, are there any active examples of this script in use?

    • Posted on February 16th, 2009 at 3:43 pm
  26. #26 Bobby says...

    Nevermind the positioning. I found it in the jquery.js file.

    Thanks

    • Posted on February 16th, 2009 at 3:48 pm
  27. #27 Matt says...

    Bobby, you can take a look at the example link, located near the top and bottom of this post.

    Are you clear about the positioning/formatting of the anchor? You can insert that however/where ever you want.

    Thanks for the comments!

    • Posted on February 17th, 2009 at 9:31 am
  28. #28 Daniel says...

    I’m having with the opacity on IE7. Any idea what to do?
    While the panel slides up or down in becomes transparent. Once stop sliding it does become solid, and cover whats behind.

    • Posted on February 19th, 2009 at 3:51 pm
  29. #29 Matt says...

    Hey Daniel, could you provide a like so I can take a look? I am not exactly sure what you are talking about here.

    Thanks

    • Posted on February 20th, 2009 at 12:37 pm
  30. #30 rulo says...

    yeah, here’s another bump for multiple div’s, that would be great!!!

    • Posted on February 23rd, 2009 at 3:18 am
  31. #31 Mike Oley says...

    Bump for Multiple DIVS

    • Posted on March 6th, 2009 at 5:17 pm
  32. #32 Jamie says...

    “This doesn’t work when you’re working with Search Engine-Friendly URLs (subdirectories), only works with files inside the same “folder”.”

    Anyway to change this?

    • Posted on May 7th, 2009 at 8:41 am
  33. #33 JQuery - Ebenen ein/ausblenden - jswelt - Forum (Javascript, PHP, MySQL, AJAX, Webdesign) says...

    […] was bewegt und das er bei F5 dr

    • Posted on May 7th, 2009 at 5:36 pm
  34. #34 Jay says...

    Is there a way to reverse this entirely so the toggle is visible at first, and when you hide it, it will remain hidden as you go thru the pages?

    • Posted on May 15th, 2009 at 6:22 pm
  35. #35 Matt says...

    Hey Jay, it should be as easy as removing the line:

    $(”#panel”).hide();

    • Posted on May 20th, 2009 at 10:23 am
  36. #36 JRock says...

    I’m having trouble getting this to work in IE 7. Being new to javascript and jQuery, is this a problem with the plug-in or jQuery itself? Any idea how to correct it?

    It works fine in Firefox and IE 8 though…

    Thanks!

    • Posted on May 22nd, 2009 at 12:35 pm
  37. #37 JRock says...

    To clarify my original message, this isn’t working at all in IE7. The page renders, but the toggle text doesn’t highlight as a link, so there’s no interaction. Again, perfect in Firefox, etc.

    • Posted on May 22nd, 2009 at 12:40 pm
  38. #38 Matt says...

    @ JRock - I am not sure what you mean by no interaction. I just tested it on Windows IE7, is this a Mac issue?

    Are you using the exact markup?

    • Posted on May 22nd, 2009 at 2:06 pm
  39. #39 JRock says...

    Yes, however, I’m also using several other jQuery plug-ins as well, including on that also uses the cookie plug-in. I removed the slider feature and the page worked along with all the other functionalities.

    Is it possible that there is a conflict going on in IE with more than one function making use of the cookie plug-in?

    This is on a PC.

    Thanks for the prompt response!

    • Posted on May 22nd, 2009 at 2:36 pm
  40. #40 JRock says...

    Another thought, I’m using the latest jQuery (1.3.2) does this plug-in use an older version?

    • Posted on May 22nd, 2009 at 3:03 pm
  41. #41 jldesign says...

    Hi, great tutorial and script. I used it on my web site to show comments:

    http://www.rubin-meble.pl

    It works perfectly. Thank You!

    • Posted on June 1st, 2009 at 11:24 am
  42. #42 Joe says...

    Nice script, I’ve been trying to modify this script to cater for multiple divs. No Success so far!

    Need it to be clean and not a matter of copying all the jQuery code for a different div id.

    Anyone had any success here?

    • Posted on June 16th, 2009 at 8:17 pm
  43. #43 Dm says...

    Hi Klaus.

    Sorry to take your time im useing your jq.
    I would like this in my users infopanel, when you click on the panel it stays up, and again it stays down, but done everything and its not working, im terrible with js but still trying.
    Coluld you give me some help or a hint ehat should i do?.
    Sorry for my bad english

    • Posted on June 19th, 2009 at 2:59 am

Tell us how you really feel.

 



Sponsors