Home > front end >  A task with displaying clicks on a given button (Javascript)
A task with displaying clicks on a given button (Javascript)

Time:07-04

Make a button that displays the number of clicks on it. If the next click occurs faster than a second after the previous click on the button, the button is blocked (use the disabled attribute), the click counter is reset to zero.

My attempt:

const buttons = document.getElementById(`button`);

buttons.onclick = function () {
  buttons.disabled = true;
  setTimeout(function () { buttons.disabled = false }, 1000);
  console.log(`click`)
}

buttons.addEventListener('click', () => {
  console.log(`Bbb`);
  let clicks =  this.dataset.clicks;
  clicks  = 1;
  console.log(clicks);
  this.dataset.clicks = clicks;
});

CodePudding user response:

const btn = document.getElementById('button');
let clicks = 0;

btn.addEventListener('click', function () {
  clicks  = 1;
  console.log('click');
  this.innerHTML = clicks;
});

I discourage posting mere solutions for coding exercises, but I don't really know how to explain this, lol.

Is this the behavior you want to achieve?

CodePudding user response:

Using a helper function that returns current time in ms, we just store every click the time, and compare it to last one.

function now() {
  return (new Date()).getTime();
}

const button = document.getElementById(`button`);


button.addEventListener('click', function() {
  if (this.last && now() - (this.last) < 1000) {
    this.innerText = "0"
    this.disabled = true;
    return;
  }
  let clicks = parseInt(this.innerText, 10);
  clicks  = 1;
  this.innerText = clicks;
  this.last = now();
});
button {
  width: 200px;
  height: 40px;
}
<button id="button">0</button>

  • Related