Limit button clicks

Hello, I want to make a button for a page, but that button can only be pressed once every 24 hours

Button:


<button onClick="randomAlerts();">Click Me</button>
<div id="response"></div>

<style>
body {
  margin: 0 auto;
  width: 100%;
  text-align: center;
}
button {
  margin: 0 auto;
  width: 200px;
  height: 3em;
  //border: 1px solid lightgray;
  //border-radius: 5px;
  background-image: linear-gradient (to bottom,
    white 10%,
    lightgray 15%,
    gray 85%,
    black 100%);
}
#response {
   //border: 1px solid lightgray;
    margin: 0 auto;
  line-height: 3em;
  color: orange;
  font-family: sans-serif;
  font-size: 2em;
}
</style>

<script>
function randomAlerts() {
    var alerts = new Array (
    "1",
    "2",
    "3",
    "4",
    "4");
    
    i = Math.floor(Math.random()*alerts.length);
    var div = document.getElementById('response');
    div.innerText = alerts[i];
}

</script>

You should probably use Cookies or a rate limit. Look up “HTML/JS Cookies” online for a great tutorial.

Hi @l4zarus!
Welcome to the Glitch community :glitch: :slight_smile:

There are a few options of going about this, here are some of my suggestions

Only clickable once every 24hrs for each user
As @will suggested cookies is a good idea. You should set a cookie that expires in exactly 24 hours from when it’s created and then check for whether the cookie exists when someone clicks the button. This is a good guide for JS cookies: JavaScript Cookies or sometimes it might be easier to use a package, like this one: GitHub - js-cookie/js-cookie: A simple, lightweight JavaScript API for handling browser cookies (I usually use the CDN to put it directly into my HTML).

Only clickable once every 24hrs by one person worldwide
If I were making this I would probably make a script that saves to a JSON file whenever someone clicks the button, with the date they clicked the button. Then whenever someone tries to click the button, it would read most recent entry in the JSON file and check if its date that is less than 24 hours ago, than the button won’t work, whereas if the entry’s date was more than 24 hours ago the button will work and another entry will be made in the JSON with the current date. Then you could do really cool stuff by parsing the JSON file whenever someone goes on the page so you can say e.g. how many times people have clicked the button (use jsonfilevariable.length), how long is left until the button will be available again, etc. For more details on JSON files in JS, see these guides:
Reading the JSON file: How to read an external local JSON file in JavaScript? - Stack Overflow
JSON file format: JSON Syntax
etc.

Hope this helps!
Eddie

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.