Keeping toggled class after page refresh

我的梦境 提交于 2019-11-28 11:51:35

Cookie approach

You can use a jQuery plugin such as jquery-cookie to simplify cookie access. So your code would become something like this to save the class setting:

$(document).ready(function() {
    var body_class = $.cookie('body_class');
    if(body_class) {
        $('body').attr('class', body_class);
    }
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
        $.cookie('body_class', $('body').attr('class'));
    });
});

URL Parameters

Another option would be to set a URL parameter on all the links the page when they click #switcher to maintain the state without setting a cookie.

Use cookies or the brand new local storage introduced with HTML5. You can also create some server session solution where you get previous settings through an AJAX call or so.

You will definately need to use cookies for this.

First of all you need to download the jQuery cookie plugin and add it to your page.

Then in your example above you'll need to set the cookie when the body class is changed:

$("a#switcher").click(function() {
    $("body").toggleClass("alternate_body");
    $.cookie('bodyClass', 'alternate_body');
});

Then on page load, check for the cookie and set the body class as required:

$("BODY").addClass($.cookie('bodyClass'));

you could use cookies to save it after a pagerefresh. just save the class in a cookie and read it when you need it (after refresh). if you don't know how cookies work, follow the example here:

http://www.electrictoolbox.com/jquery-cookies/

a second option is to call a php function to save it into a database (i don't know this is for users when they are logged in? ) but else you can save it in the database to save it and read it later so when somebody deletes his internet history, or go to another computer he has the same layout.

greets, stefan.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!