开发者

Preserving the state of show/hide sections in Django with jQuery/Javascript

I have a form with some show/hide sections. When I press some buttons in my home form, different forms will be shown. After I edit the information in those forms I'm returning to the first form. But the state of the show/hide sections is reseted. The show/hide action is done with jquery toggle. The state of these sections needs to be kept on returning. So I'm开发者_如何学编程 thinking of storing the state of each section in session variables. Do you have other solutions? Would it be better or possible to have this behavior in a separate place, for example in a middleware?


You don't really need session storage. In the case you've described, you want the sections' show/hide status to be kept between pages, for a single client. Session would be overkill, as it involves the server for something trivial.

My go would be to use something like localStorage (or cookies if you really want) directly in the jQuery. It will stay on the client and the server will not mind.

EDIT

Function to check for localStorage:

var canHazStorage = function () {
    "use strict";
    try {
        return 'localStorage' in window && window.localStorage !== null;
    } catch(e) {
        return false;
    }
};

You would need to change the toggling code to set a value:

$('#section1').toggle();

if ( canHazStorage ) {
    if ( is_shown ) { // you'll need to write that yourself
        window.localStorage['section1'] = true;
    } else {
        window.localStorage['section1'] = false;
    }
} else {
    // same code using cookies
}

And in init function:

if ( canHazStorage ) {
    var toggled = window.localStorage['section1'];
    $('#section1').toggle(toggled);
} else {
    // same code using cookies
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜