This code has been checked for errors and none were detected. But, when it runs, it alerts null.
For Sololearners my code bit: https://code.sololearn.com/WOv1cF0EewdB/?ref=app
Why is this?*
window.onload = function() {
let reload_interval= setInterval(rel, 120000);
if (localStorage.getItem('visit') !== true) {
let username = prompt('Enter your name:');
if (confirm('Do you want to be known as ' username ' from now on?')) {
localStorage.setItem('name', username);
} else {
username = prompt('OK then, enter your name:');
if (confirm('Do you want to be known as ' username 'from now on?')) {
localStorage.setItem('name', username);
}
}
localStorage.setItem('visit', true);
}
if (localStorage.getItem('visit') === true) {
document.getElementById('p').innerHTML = localStorage.getItem('name');
alert('Hello, ' localStorage.getItem('name'));
}
};
function clearLocalStorage() {
if (confirm('Do you want to clear current username data?')) {
localStorage.clear();
alert('Cleared');
}
}
*jQuery answers are OK
CodePudding user response:
You are not getting a hello alert is because you are checking getItem
's return value with === true
and !== true
.
setItem
will convert your value to string
, so localStorage.getItem('visit') === true
will never be true
If you want to check if the user has visited the page, you should use === "true"
(visited) and !== "true"
(not visited) since it returns string
.