views:

142

answers:

1

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.

A: 

I think it should work if you simply swap around the show() and hide() function

line 25:

 panel = obj.find(op.group).hide(),

to

 panel = obj.find(op.group).show(),

line 33

 panel.eq(c).show();

to

 panel.eq(c).hide();

then again i think you are using way too complicated code if you want to hide/show just 1 element

Zumo