user3658656
user3658656

Reputation: 11

Local storage JavaScript in HTML

I'm making a craft beer webpage, and I want users to type in their age before entering. The initial prompt works, but if I switch tabs and go back to home page I am prompted again.

Question: How do I only get one prompt and save it until user exits the whole webpage including navigating tabs.`

My script:

<script>

function CloseWindow(){
window.open('','_self','');
window.close();
}
</script>

<script>
var age;
age = prompt("Please enter in your age: ");
if (age >= 21){
   alert("Age is valid");
}
else{
   alert("Not valid age");
   CloseWindow();
}
</script>

Upvotes: 0

Views: 185

Answers (3)

Richard Kho
Richard Kho

Reputation: 5286

Use the window.localStorage object to store the user's age. This will allow the information to persist through pages.

if (window.localStorage && !window.localStorage.age) {
     //Your code here to prompt the user's age and save it in window.localStorage.age
} else {
    //Your code here to prompt the user's age and save it in document.cookie
}

Upvotes: 1

boombox
boombox

Reputation: 2456

Below is an example snippet on how you can incorporate localStorage by building on top of your code. You can clean it up for what you need. If you want an alternative that resets when you close your browser, you can just replace localStorage with sessionStorage.

 function CloseWindow() {
   window.open('', '_self', '');
   window.close();
 }

 var validAge = localStorage.getItem('validAge');
 if (!validAge) {
   var age;
   age = prompt('Please enter in your age: ');
   if (age >= 21) {
     alert('Age is valid');
     localStorage.setItem('validAge', 'true');
   } else {
     alert('Not valid age');
     localStorage.setItem('validAge', 'false');
     CloseWindow();
   }
 } else if (validAge === 'true') {
   alert('Age is valid');
 } else if (validAge === 'false') {
   alert('Not valid age');
   CloseWindow();
 }

This is a link that shows some localStorage polyfills for outdated browsers.

Upvotes: 1

ablais
ablais

Reputation: 1426

In order to do that, you need to create a variable in the local storage and check its content before running the whole function again. I suggest you check online for tutorials how to do that, here's one I found for you : http://diveintohtml5.info/storage.html

Here's an example of how to do it simply too :

//Get the variable from the local storage
var age = localStorage.getItem('age') || 0; //instead you get nothing

if (age >= 18) {
   //access the website
} else {
   //here's where you run your function
   //...

   //Set the local storage variable
   localstorage.setItem('age', age) //where *age* is the name of the function's variable

}

I hope this will helps ! Good luck ;)

Upvotes: 0

Related Questions