I've a div that will show the success message after successful login and will hide after 4 seconds. The js code used is
document.getElementById('success').style.display = 'none';
}, 4000);
This works fine. But this div will pop up every time I navigate to home page and I don't want that to happen. This div should be in hidden state until logged out and logged in again. It would be better to have a solution that wont use jquery as this is a project. I've tried sessionStorage also but that hides the div immediately after showing and not lasting 4seconds.
Thanks in advance
const alreadyShown = localStorage.getItem('alreadyShown');
if (alreadyShown === 'true') {
document.getElementById('success').style.display = 'none';
}
setTimeout(() => {
localStorage.setItem('alreadyShown', 'true');
document.getElementById('success').style.display = 'none';
}, 4000);
you can use js localStorage. localStorage is similar to sessionStorage, except that while localStorage data has no expiration time
You can do something like this:
To check if user has successfully logged in. you can set a key/value pair in session storage after successful login. we will delete this key/value pair when we logged out from the website.
So when user redirects to home page the first thing we will do it check if "loggedIn" key is there in session storage or not.
const isLoggedIn = sessionStorage.getItem('loggedIn');
if(!isLoggedIn) {
document.getElementById('success').style.display = 'block';
setTimeout(() => {
document.getElementById('success').style.display = 'none';
sessionStorage.setItem('loggedIn', true);
}, 4000);
}
So now on first time user redirects to home page then the success message will be displayed and the "loggedIn" key will be set to session storage. if user redirects back to home page there will be key so we will not display message. now all you need to do is to delete this "loggedIn" key from the session storage whenever you logged out. You can delete the key by
sessionStorage.removeItem('loggedIn');
now the key is deleted after log out. it will display success message on successful loin for the first time.
Make display to none by default and toggle to block when required
You can achieve your required behavior by reversing your implementation.
Set display to none by default
Convert to block after clicking login and authentication
Set a timer for 4 seconds ( to display the login message )
Set display back to none.
document.getElementById("app").style.display = "block";
setTimeout(
() => (document.getElementById("app").style.display = "none"),
4000
);