Keeping toggled class after page refresh

2019-01-19 09:16发布

am thinking this has been done many times before but despite reading some posts about cookies couldn't get my head round it.

I basically have a second body class with different fonts for the whole site which is accessed when the clients clicks a link to change font. Ideally this wouldn't be on a page-by-page basis but the new class would 'stick' after a new page is visited. My change class code via jquery looks like this:

$(document).ready(function() {
    $("a#switcher").click(function() {
        $("body").toggleClass("alternate_body");
    });
});

Is there a relatively simple way of achieving this? Thanks in advance.

4条回答
再贱就再见
2楼-- · 2019-01-19 09:47

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'));
查看更多
我命由我不由天
3楼-- · 2019-01-19 09:48

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.

查看更多
再贱就再见
4楼-- · 2019-01-19 09:49

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.

查看更多
萌系小妹纸
5楼-- · 2019-01-19 10:03

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.

查看更多
登录 后发表回答