save .addClass with jQuery cookie or local storage

强颜欢笑 提交于 2019-12-07 02:42:30

Here is a way to use localstorage:

Given this markup (I am using input type="radio" for this example):

<div class="btn-group" data-toggle="buttons" id="btn-switch">
  <label class="btn btn-default">
    <input type="radio" id="option1" name="options" value="1" data-color="{T_THEME_PATH}/normal.css" autocomplete="off"> off
  </label> 
  <label class="btn btn-default">
    <input type="radio" id="option2" name="options" value="2" data-color="{T_THEME_PATH}/inverse.css" autocomplete="off"> on
  </label> 
</div>
<br><br>
<a id="bg" href="{T_THEME_PATH}/normal.css">Background</a>

In the script, listen for the change event on the radio buttons. This is fired for any radio that is checked. First set the #bg href to the clicked radio's color data-attribute (Use jQuery .data()). Then store this href to localstorage. Additionally store the ID of the clicked option to localstorage. Then on subsequent page loads use the items in localstorage to set the correct href and activate the correct radio button:

$(document).ready(function() {
    var csshref = localStorage["css"];
    if (csshref) {
        $("#bg").prop("href", csshref);
    }
    var activeid = localStorage["activeid"];
    if (activeid) {
        $("#" + activeid).prop("checked", true).closest("label").addClass("active");
    }

    $('#btn-switch [type="radio"]').on("change", function() {
        $("#bg").attr("href", $(this).data('color'));        
        localStorage.setItem('css', $(this).data('color'));        
        localStorage.setItem('activeid', $(this).prop('id'));        
        return false;
    });
});

Here is a DEMO

In the demo, try checking on and off and then hittin RUN again. You will see that subsequent runs remember which item was checked and set the href appropriately.

Here is a simple way to do it:

    $(document).ready(function () {
        //on page load check for cookie value and add active class
        if($.cookie("isButtonActive") == 1)
        {
            $("#btn-switch button").addClass("active");
        }

        $("#btn-switch button").click(function() { 
           //your previous code here
           if($("#btn-swtich button").hasClass("active") == true)
           {
               //button was active, de-activate it and update cookie
               $.("#btn-switch button").removeClass("active");
               $.cookie("isButtonActive", "0");
           }
           else
           {
               //button is not active. add active class and update cookie.
               $.("#btn-switch button").addClass("active");
               $.cookie("isButtonActive", "1");

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