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!

18 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

Tell us how you really feel.

 



Sponsors