There are already solutions here using localStorage
; however, a value set in localStorage
will remain until the user clears their browser data. This means that your code will never run again unless you specifically do extra work to check how long it has been set, etc.
If you would like it to run again when they visit the page later you should use sessionStorage:
...data stored in sessionStorage gets cleared when the page session
ends. A page session lasts for as long as the browser is open and
survives over page reloads and restores. Opening a page in a new tab
or window will cause a new session to be initiated, which differs from
how session cookies work.
This will allow the code to run on a new visit to the page, but reloading or navigating away/back will not trigger it because the sessionStorage
is still set. However, if they close the tab/window and come back to it later, the code will run again.
$(document).ready(function() {
if(!sessionStorage.visited) {
sessionStorage.visited = true;
...
//other code
}
});