If the user's browser reloads your site upon returning to the homepage (not a single-page app), your scripts will reset as well, causing the count
value to be lost. This value is essential for tracking the user's previous visit.
To address this issue, you can either use a cookie, or utilize either sessionStorage
or localStorage
.
// sessionStorage or localStorage (both work the same way)
if (!sessionStorage.getItem('hasVisited')) {
$(".fade-in-first").addClass("animated fadeInUp");
setTimeout(function(){
$(".fade-in-second").animate({ opacity: 1 });
$(".btn-explore").addClass("pulse-anim");
}, 1300);
sessionStorage.setItem('hasVisited', true);
}
Use sessionStorage
if you only need to track their homepage visit for the current session. The stored data is available until the tab, window, or browser is closed. Note that sessionStorage behavior may vary across tabs due to how browsers handle tab history.
Choose localStorage
if you want the value to persist across different sessions and tabs. All browsing tabs on your site share the synchronized localStorage object.
Note 1: It's advised to manipulate values in the Web Storage API
(session/localStorage
) using setItem() / getItem()
to prevent issues with inherited prototype values and accidental property overwrites.
For instance:
localStorage.key = 'My key value';
console.log(localStorage.key);
In the above scenario, the assigned value is accessible but inadvertently replaces the key
method of the localStorage object!
Note 2: These values are limited to the same subdomain and protocol! Crossing subdomains or protocols won't retain the information from www.example.com
to login.example.com
, or transitioning between http://www.example.com
and https://www.example.com
.
Cookies
Cookies offer an alternative solution, although parsing values requires more effort (especially when already using jQuery). Pay attention to set the appropriate path
for the cookie's scope and consider the expires
attribute. Refer to these resources for additional details:
https://www.w3schools.com/js/js_cookies.asp
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie