6

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>
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Anna
  • 93
  • 1
  • 1
  • 6

2 Answers2

11

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 = {/*...*/};
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks for all that information, that was great! In my javascript, it is basically changing two
    from hide to show. am i able to set the item and get it using this then?
    – Anna Apr 07 '18 at 14:10
  • @Anna: Yes, you might use the code shown above for getting your `settings` object on page load, perhaps defaulting to `{showDiv1: false, showDiv2: false}`, then update and store that object when you want to set those flags to `true` (or back to `false` again). – T.J. Crowder Apr 07 '18 at 14:14
  • do i just use the JSON part?Sorry new to all this javascript! – Anna Apr 07 '18 at 14:25
  • @Anna: Yes, the `var settings = JSON.parse(localStorage.getItem("settings"));` near the beginning of your script (and the `if` that follows it to set up a default the first time), and then the `localStorage.setItem("settings", JSON.stringify(settings));` for when you want to save your settings. – T.J. Crowder Apr 07 '18 at 14:37
  • OK, i'm just not entirely sure what i put into "settings" to get it saved, and where the showDiv1 and 2 can be defined then? – Anna Apr 07 '18 at 14:40
2

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

Not really. A key difference in Cookies and Local Storage is that cookies will be sent along with every server request you make.[1]

  • Requesting some data using AJAX, cookies will be included in the request.

  • Navigating to a new page, cookies will be included in the request.

So the disadvantage is that you are transferring additional data to the server every time you make a request. More so if you are storing a lot of data into the cookies.

Local storage is merely kept in the browser (until you clear it explicitly), but it is not sent along with every request.

The decision is simple, if you require that data available to the server with request parameters, you should use cookies, else use local storage.


One more thing, from what you are saying, it seems like you intend to store the user's progress in a game. Keep in mind that both cookie and local storage are accessible to the user. So they can tamper with that data if they want.

If it is critical to prevent user's from changing the data, you must store the data on the server instead.

Do read: JavaScript: client-side vs. server-side validation


[1]. This may not be entirely true with HTTP2 but that's a different topic.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • thanks for this. I don't want to store on the server, local storage is probably the best but i'm just not sure how to go about it? Do you have any advice? – Anna Apr 07 '18 at 14:12
  • @Anna As T.J. Crowder explains, converting objects to JSON string is pretty much the standard way of storing stuff into local storage. – Nisarg Shah Apr 07 '18 at 14:15
  • ah yes ok. Can you help me put it into perspective of my code? – Anna Apr 07 '18 at 15:21
  • @Anna I am not sure I can help with that, as I don't know your application much. But I would recommend that you go through MDN's [documentation of localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), and then [the article on Web storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API). They have a good example application. – Nisarg Shah Apr 07 '18 at 15:29
  • basically I’m using class = ‘hide’ and ‘show’ to hide and show items on a page. When a button is selected one gets hidden and one gets shown. – Anna Apr 07 '18 at 15:33
  • @Anna as I said, its a bit broad. I would suggest that you read the two articles I linked in my previous comment. They cover everything you need to know about localStorage. If you are still unsure after reading them, I would suggest creating a minimal example showing your problem, and your attempt at solving it. You can post that in a new question, and provide a link to this question for context. But do read about how to create a [mcve] before posting the question. – Nisarg Shah Apr 07 '18 at 15:40
  • @Nisarg, Great answer! – NicuVlad May 04 '19 at 13:37