Tahmid Tahmid - 1 year ago 63
CSS Question

Remembering if javascript was run before and not running it again if it was [EnjoyHint.js]

I am currently using EnjoyHint.js on my website (its basically for website walkthroughs/tours). The .js file which initialises the tour runs each time I reload the page. This means the tour keeps appearing even if you have seen it already when reloading the page or visiting it a second time. I am unsure of how to stop this from happening. I only want the .js script to run once and not run again if the user reloads or visits the page again.

Is it possible to remember if the .js file was run on the computer before and not run it again if it was. If someone visits the website, I don't want the website tour to keep appearing if they have already seen it once before.


Answer Source

Using cookies is common for this kind of task. There are plenty of libraries to use them in an easy way, but for this, you don't really need one:

// If the cookie is not set to 1
if(document.cookie.indexOf('tourIsDone=1') < 0){
    //Launch the tour
    // Set the cookie (you can also do it once the tour is finished)
    document.cookie = "tourIsDone=1";

Explanation, since document.cookie can be confusing

When reading document.cookie, you get a long String containing every cookie :


Checking for document.cookie.indexOf(nameOfCookie) < 0 will make sure it's not in there.

However, in order to set a single cookie without changing the others, you just need to do:

document.cookie = "newCookie=newValue";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download