最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cookies - I want to save user preferences on a javascript code - Stack Overflow

programmeradmin0浏览0评论

I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.

<script type="text/javascript">
    $(document).ready(function() {
        $("#fullswitch").click(function() {
            $("#chpheader").removeClass("pact");
               $("#imgg").removeClass("pact");
               $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
                            $("#chpheader").addClass("normal");
            $("#imgg").addClass("normal");

        });
        $("#pactswitch").click(function() {
            $("#chpheader").addClass("pact");
            $("#imgg").addClass("pact");
            $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });
          $("#originalswitch").click(function() {
            $("#chpheader").addClass("original");
            $("#imgg").addClass("original");
            $("#chpheader").removeClass("pact");
               $("#imgg").removeClass("pact");
                            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });

    });
</script>

I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.

<script type="text/javascript">
    $(document).ready(function() {
        $("#fullswitch").click(function() {
            $("#chpheader").removeClass("pact");
               $("#imgg").removeClass("pact");
               $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
                            $("#chpheader").addClass("normal");
            $("#imgg").addClass("normal");

        });
        $("#pactswitch").click(function() {
            $("#chpheader").addClass("pact");
            $("#imgg").addClass("pact");
            $("#chpheader").removeClass("original");
            $("#imgg").removeClass("original");
            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });
          $("#originalswitch").click(function() {
            $("#chpheader").addClass("original");
            $("#imgg").addClass("original");
            $("#chpheader").removeClass("pact");
               $("#imgg").removeClass("pact");
                            $("#chpheader").removeClass("normal");
            $("#imgg").removeClass("normal");

        });

    });
</script>
Share Improve this question edited Aug 11, 2011 at 21:38 lucapette 20.7k6 gold badges67 silver badges59 bronze badges asked Aug 11, 2011 at 20:20 syrkullsyrkull 2,3444 gold badges36 silver badges68 bronze badges 0
Add a ment  | 

7 Answers 7

Reset to default 3
<html>
<body>
 <span id="t1">0</span> 
 <span id="t2">0</span>
 <span id="t3">0</span> 
 <span id="t4">0</span>
 <span id="t5">0</span>
 <span id="t6">0</span> 
<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
  // Store
  localStorage.setItem("lastname", "Smith");
   localStorage.setItem("first", "Smi");
  // Retrieve
  var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
 var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>

</body>
</html>

There is a jQuery cookie plugin there are examples on that page as well so you can see how you can set and read a value from the cookie.

Once the value is read it's just a simple matter of loading the right theme.

var theme = $.cookie('name_of_selected_theme');
setTheme(theme);

function setTheme(themeName){
   if(themeName == "One"){
     ...
   }else...
}

However cookies only allow for 4KB of data and are passed in every HTTP call. A better idea many be localStorage. You can use YUI Storage Lite library which is < 3KB in size and you can easily use it to save data in browser localStorage and load from it. You can save at least 5MB of data using localStorage.

Example code from the link above:

YUI({
    //Last Gallery Build of this module
    gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {

    // For full patibility with IE 6-7 and Safari 3.x, you should listen for
    // the storage-lite:ready event before making storage calls. If you're not
    // targeting those browsers, you can safely ignore this step.
    Y.StorageLite.on('storage-lite:ready', function () {

        // To store an item, pass a key and a value (both strings) to setItem().
        Y.StorageLite.setItem('kittens', 'fluffy and cute');

        // If you set the optional third parameter to true, you can use any
        // serializable object as the value and it will automatically be stored
        // as a JSON string.
        Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);

        // To retrieve an item, pass the key to getItem().
        Y.StorageLite.getItem('kittens');    // => 'fluffy and cute'

        // To retrieve and automatically parse a JSON value, set the optional
        // second parameter to true.
        Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']

        // The length() method returns a count of how many items are currently
        // stored.
        Y.StorageLite.length(); // => 2

        // To remove a single item, pass its key to removeItem().
        Y.StorageLite.removeItem('kittens');

        // To remove all items in storage, call clear().
        Y.StorageLite.clear();

    });

});

I suppose you have two options, store the info client side, or store the info server side.

If you actually have a "user" server side (the person has to log in, yada yada yada), you can store this setting for the user (add some data to where ever the user info is stored).

If you don't want it that persistent, you can store it in local storage (not very browser friendly) or cookies. You really have no guarantee that these settings will stay around, as they are controlled by the browser, users can have their browsers set to never save this info.

Either way (client or server) you can read the setting and set the classes server-side and skip the javascript for changing the classes. Always better to do it on the server.

You may use HTML5 window.localStorage to store user preferences and trigger the corresponding layout changes.

Or use cookies as previously suggested.

Take a look at this article: http://diveintohtml5.ep.io/storage.html

Use cookies to store the users options.

http://www.quirksmode/js/cookies.html

Use localStorage to store the user preferences, and on reload load the preferences back in.

Here's a good tutorial.

How to write: localStorage['someKey'] = 5;
How to read: var lastKeyValue = localStorage['someKey'];

use session storage

   //set in session storage
    $("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
      //in that case one expanded at the time
      sessionStorage.clear();
       var par = $(evt.target).parent();
       sessionStorage.setItem(par.attr('id'),par.attr('class'));    
       console.log(par.attr('class'));         
    });


 //    //retrieve class from session
if(typeof sessionStorage!='undefined') {
    $('#block-menu-menu-organisation > ul > li' ).each(function(i)  {           
        if( $(this).attr('id') in sessionStorage) {     
            $(this).attr('class', sessionStorage.getItem($(this).attr('id')));          
        }
        });
}
发布评论

评论列表(0)

  1. 暂无评论