Search code examples
javascriptjquerycookiessession-cookiessetcookie

Display info box when user clicks only once in 24h


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

Solution

  • 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>