admin管理员组

文章数量:1184877

I have this code that shows alert when it's 30 minutes before event in calendar but I want to show it only once when user comes to page (in that 30min). Now it shows on every page refresh and also on calendar refresh (in that 30min) because it is set to refresh events after period of time. How to display this alert just once?

var mili = event.start.getTime() - now.getTime();
if(mili < 1800000 && mili > 0){    
$('.alert').dialog({ 
        buttons: [{ 
        text: "OK", 
          click: function() { 
            $( this ).dialog( "close" ); 
          }
        }]
    });
}

I have this code that shows alert when it's 30 minutes before event in calendar but I want to show it only once when user comes to page (in that 30min). Now it shows on every page refresh and also on calendar refresh (in that 30min) because it is set to refresh events after period of time. How to display this alert just once?

var mili = event.start.getTime() - now.getTime();
if(mili < 1800000 && mili > 0){    
$('.alert').dialog({ 
        buttons: [{ 
        text: "OK", 
          click: function() { 
            $( this ).dialog( "close" ); 
          }
        }]
    });
}
Share Improve this question asked Jul 15, 2014 at 20:58 JakobJakob 3,5464 gold badges27 silver badges42 bronze badges 1
  • 1 Have you tried cookies or localStorate? – PeterKA Commented Jul 15, 2014 at 21:00
Add a comment  | 

4 Answers 4

Reset to default 22

You can use localStorage (not compatible with older browsers):

<script type="text/javascript">
    var alerted = localStorage.getItem('alerted') || '';
    if (alerted != 'yes') {
     alert("My alert.");
     localStorage.setItem('alerted','yes');
    }
</script>

Or you can use cookies, give a look to this answer for a full example code: https://stackoverflow.com/a/21567127/3625883

Set a cookie when you show the alert. Then, if the cookie is set, you will know not to show the alert again. If it is not set, you know that you haven't shown the alert yet and should do so now.

You can read about setting cookies in JavaScript here.

I know this is late but you definitely don't have to use local storage or cookies. I was disheartened by the answer here so I found my own solution.

Use a boolean and an embedded if statement.

var alerted = false;

if (x > y)
{
     y = z;
     if (alerted === false)
     {
          alert("show your message");
          alerted = true;
     }
}

You can then reset the alerted variable later on if you want to show the alert message again.

You have to use cookies or localStorage or sessionStorage to do this!

See the following link on localStorage: http://www.w3schools.com/html/html5_webstorage.asp

or

http://www.webdesignerdepot.com/2013/04/how-to-use-local-storage-for-javascript/

本文标签: javascriptDisplay alert only onceStack Overflow