DEV Community

Ben Douglas
Ben Douglas

Posted on

Creating a Simple Multi Click Button in Javascript

What we are making

Note: Hey! This is my first post on dev.to :) I would appreciate a follow if you like the post and want more!

Recently I was thinking about how common the action of tapping something a certain number of times on mobile apps triggers an action (ex. double click), but I have never seen that method being used on the web.

So I thought it would be interesting to implement a multi click button for fun in javascript.

Demo

https://glitch.com/edit/#!/multi-click?path=public/client.js:1:0

The process

Essentially instead of having an action trigger immediately, you wait a small amount of time, and if the button is pressed again before the timer runs out the, you count another click and restart the timer.

The JavaScript

// total number of clicks in a sequence of button presses
var clicks = 0;

// speed in ms of how long the space between clicks can be
// the lower the number, the more responsive clicks will feel
var wait = 300;

const trigger = document.getElementById("trigger");
const response = document.getElementById("response");

var timer = null;

trigger.onclick = function() {
  response.innerHTML = "waiting...";
  clicks++;

  clearTimeout(timer);

  timer = setTimeout(function() {
    response.innerHTML = "Clicks: " + clicks;
    clicks = 0;
  }, wait);
};

Enter fullscreen mode Exit fullscreen mode

Conclusion

The real challenge of developing a multi click button is finding the perfect timeout between clicks. If the delay is too long, the button will feel unresponsive. If the delay is too short, then it may be too fast for the user and cause them to trigger the wrong action.

The default response time on windows is 500ms, but I found 300ms was more than enough time between clicks.

I hope you enjoyed my first tutorial! I would appreciate a follow if you like the post and want more.

Top comments (0)