-1

I want to display an info box, when a user clicks anywhere at my site. It works very well, but the info box should only be displayed once in 24 hours. So I need to set a cookie, but unfortunately I couldnt figure out how.

<script>    
    document.onclick = function (event) {
        alert("Some info box");
    };    
</script
Rajan Goswami
  • 769
  • 1
  • 5
  • 17
Vaze
  • 51
  • 1
  • 6
  • Assuming here you mean once per user? Cookie would be a good way to do it though yeah, have a look at https://github.com/js-cookie/js-cookie - it's pretty easy to get set up. – thecraighammond Aug 13 '15 at 12:44
  • 1
    Naturally you already have read [all these](http://stackoverflow.com/search?q=[javascript]set+cookie)? – Teemu Aug 13 '15 at 12:45

2 Answers2

1

You could use document.cookie for that. Here's an article on it: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie.
For your purposes, you would need something like:

<script>


  document.onclick= function(event) {

  // Check if the cookie is set
  if (document.cookie.indexOf("alert=true") == -1) {
      alert("Some info box");
      // Set a cookie to indicate the alert has been displayed.
      // Expiration time is 60 seconds * 60 minutes * 24 hours
      document.cookie = "alert=true; max-age=" + 60 * 60 * 24;
  }


    };
  </script>
BurningLights
  • 2,387
  • 1
  • 15
  • 22
0

You have couple of things to do.

  1. First, set a cookie using document.cookie which will contain the timestamp for 24hrs from now. This should be done when the user clicks on the web page for the first time. You can show the info box at this time.
  2. Then, for every click after that, you should check whether the time now has exceeded the value of the cookie (which means simply checking whether 24 hrs has gone since the cookie was set.
  3. Only if exceeded, show the info box and update the cookie value to 24hrs from now.

I created a fiddle to demonstrate it HERE

Aruna Tebel
  • 1,436
  • 1
  • 12
  • 24