Goal is to remove local storage item after 24 hours, meaning show modal only once per day everyday. The local storage value is set. However, my condition to check if local storage item does not exist and 24 hours have passed then show modal is only half way working. I need it to expire the modal (not show) if the local storage value has been set for less than 24 hours. Currently, it is not removing the local storage item and showing the modal only once on load. If refresh page after time frame the local storage item is still there. Using Sweet Alert for modal, but that should not matter I don't think. Also not sure if I need a for loop or set time interval for this.
To make testing easier for a one minute duration you can also use:
expires = expires.setMinutes(expires.getMinutes() 1);
Here is what I tried:
$(document).ready(function() {
if (window.localStorage) {
var currentUser = '<%= current_user %>';
var swal_alert = localStorage.getItem('alert');
var currentTime = new Date($.now());
var expires = new Date();
expires = expires.setHours(expires.getHours() 24);
if (currentUser && swal_alert !=1 && currentTime < expires) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
} else {
localStorage.removeItem('alert');
}
localStorage.setItem('alert', '1');
}
}
CodePudding user response:
You are always running localStorage.setItem('alert', '1');
at the end of your function. Even if your else
clause is run, it is ineffective because you are re-setting the field right after.
Another thing to note is that your expires
will always be greater than currentTime
, because you defined expires
as currentTime 24 hours
. new Date()
just returns the current time.
One way to implement what you want is to store the timestamp of the last time the modal was shown, if it's less than 24 hours, don't show the modal, otherwise, show the modal and update the timestamp.
$(document).ready(function() {
if (window.localStorage) {
const currentUser = '<%= current_user %>';
if (currentUser && shouldShowModal()) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
localStorage.setItem('modalTimestamp', currentTime);
}
}
}
function shouldShowModal() {
const lastTimestamp = localStorage.getItem("modalTimestamp")
if (!lastTimestamp) { // modal was never shown
return true
}
const parsedTimestamp = parseInt(lastTimestamp, 10) // localStorage always store values in strings
let expiryLimit = new Date(parsedTimestamp)
expiryLimit = expiryLimit.setMinutes(expiryLimit.getMinutes() 1) // or hours...
return new Date() > expiryLimit
}
Another thing that I want to mention is that browsers do not provide APIs where you can "schedule" code like "do this after X hours". You do have setTimeout
and setInterval
functions, but they work as long the tab is active, and shouldn't be relied upon.
CodePudding user response:
You want to show modal only once per day. So, you have to keep that time somewhere to track if 24 hours have already passed since the last modal display. Here is my approach without jquery (Snippets can't access localStorage so, it may run into trouble):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Alerts once per day</h1>
</body>
<script defer>
function alertUser() {
if (localStorage.getItem('alertTime') < new Date()) {
alert('test');
var nextAlert = new Date().setSeconds(new Date().getSeconds() 10);
localStorage.setItem('alertTime', nextAlert);
console.log('avaiable');
}
}
Window.onload = alertUser();
</script>
</html>