开发者

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

开发者 https://www.devze.com 2022-12-30 21:25 出处:网络
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.

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),
       开发者_Python百科         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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消