jQuery Collapse (with cookies), default open instead of closed?

Posted by Christian on Stack Overflow See other posts from Stack Overflow or by Christian
Published on 2010-05-20T22:29:11Z Indexed on 2010/05/28 23:32 UTC
Read the original article Hit count: 344

Filed under:
|
|
|
|

Hi. I've got a jQuery snippet which basically allows a user to toggle a div, open or closed - their preference is saved in a cookie.

 (function($) {
$.fn.extend({
    collapse: function(options) {

        var defaults = {
            inactive : "inactive",
            active : "active",
            head : ".trigger",
            group : ".wrap-me-up",
            speed : 300,
            cookie : "collapse"
        };

        // Set a cookie counter so we dont get name collisions
        var op = $.extend(defaults, options);
            cookie_counter = 0;

        return this.each(function() {

            // Increment cookie name counter
            cookie_counter++;

            var obj = $(this),
                sections = obj.find(op.head).addClass(op.inactive),
                panel = obj.find(op.group).hide(),
                l = sections.length,
                cookie = op.cookie + "_" + cookie_counter;

            // Look for existing cookies
            for (c=0;c<=l;c++) {
                var cvalue = $.cookie(cookie + c);
                if ( cvalue == 'open' + c ) {
                    panel.eq(c).show();
                    panel.eq(c).prev().removeClass(op.inactive).addClass(op.active);
                };
            };
            sections.click(function(e) {
                e.preventDefault();
                var num = sections.index(this);
                var cookieName = cookie + num;
                var ul = $(this).next(op.group);
                // If item is open, slide up
                if($(this).hasClass(op.active)) {
                    ul.slideUp(op.speed);
                    $(this).removeClass(op.active).addClass(op.inactive);
                    $.cookie(cookieName, null, { path: '/', expires: 10 });
                    return
                }
                // Else slide down
                ul.slideDown(op.speed);
                $(this).addClass(op.active).removeClass(op.inactive);
                var cookieValue = 'open' + num;
                $.cookie(cookieName, cookieValue, { path: '/', expires: 10 });
            });
        });
    }
});

})(jQuery);

Demo: http://christianbullock.com/demo/

I'm just wondering how I can display the list open as default, and have the div collapse when the header is clicked?

Many thanks.

Christian.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery