Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies or localstorage is best way?

I have some javascript, in which i need either cookies or localstorage to ensure variables aren't lost. I'm a beginner and i'm not sure which is best to use, but i know both do sort of the same thing. Basically, i need whatever the javascript is doing to be stored and even when user logs out / logs in, between any amount of days this is still being saved.

Can someone help?

<script>
    $(document).ready(function() {
        $("input").click(function(e) {
            e.preventDefault();
            var $challenge_div = $(this).parent().parent();
            $challenge_div.data("finish", "false");
            $challenge_div.removeClass("show").addClass("hide");

            var $challenge_list = $("div[class='hide']");

            $.each($challenge_list, function() {
                var new_challenge = $(this);
                if (new_challenge.data("finish") == false) {
                    new_challenge.removeClass("hide").addClass("show");
                    return false;
                }
            });

            if ($("div[class='show']").length == 0) {
                $("#message p").html("You finished all your challenges !");
            }
        });
    });
</script>
like image 494
Anna Avatar asked Apr 07 '18 13:04

Anna


1 Answers

I'm a beginner and i'm not sure which is best to use, but i know both do sort of the same thing.

Actually, they do very different things.

  • Cookies are for sending information back and forth between the server and client on every HTTP request.
  • Web storage is for storing information in the client (only).

For your use case, web storage would be the right thing to use, since you only want the information client-side. It also has a reasonable API (unlike cookies). You can store a string:

localStorage.setItem("key", "value");
// or
localStorage.key = "value";    // See warning below
// or
localStorage["key"] = "value"; // See warning below

(I'd recommend using the setItem method instead of directly assigning to a property on localStorage, so there's no chance of your conflicting with any of localStorage's methods!)

...and get it back later, even in the user left the page entirely and came back:

var x = localStorage.getItem("key");
// or
var x = localStorage.key;    // See warning above
// or
var x = localStorage["key"]; // See warning above
console.log(x); // "value"

And remove it if you want:

localStorage.removeItem("key");

Often, it makes sense to use JSON to store your client-side information, by using some kind of settings object and storing it by converting it to JSON:

localStorage.setItem("settings", JSON.stringify(settings));

...and using JSON.parse when getting it (back):

var settings = JSON.parse(localStorage.getItem("settings"));
if (!settings) {
    // It wasn't there, set defaults
    settings = {/*...*/};
}
like image 125
T.J. Crowder Avatar answered Oct 09 '22 01:10

T.J. Crowder