1 year ago

#354011

test-img

Thomas

How to remove the delay until the :active class is added to a button on mobile?

On touch screens, when tapping a <button>, there is a delay of about 300 milliseconds until the :active style is applied to the button. This results in an unresponsive feeling.

In the demo below, I've added some JavaScript code to measure the delay, but the issue is visible without any JavaScript as well.

document.addEventListener('DOMContentLoaded', function() {
  const button = document.getElementById('button')
  const log = document.getElementById('log')
  
  let touchStartTime = null
  button.addEventListener('touchstart', function() {
    touchStartTime = Date.now()
  })
  
  let wasActive = false
  window.setInterval(function() {
    const isActive = window.getComputedStyle(button).backgroundColor == 'rgb(255, 0, 0)'
    if (isActive && !wasActive) {
      if (touchStartTime == null) {
        log.innerHTML += 'No touchstart event received; are you using a touch screen?\n'
      } else {
        const delay = Date.now() - touchStartTime
        log.innerHTML += `Activation delay: ${delay}\n`
        touchStartTime = null
      }
    }
    wasActive = isActive
  }, 5)
})
* {
  touch-action: none;
}

button {
  background-color: #aaffdd;
  font-size: 500%;
}

button:active {
  background-color: #ff0000;
}
<html>
  <head>
    <meta name="viewport" content="width=device-width">
  </head>
  <body>
    <button id="button">Press me</button>
    <pre id="log"></pre>
  </body>
</html>

I think I've done all the things I need to remove delays:

  • set touch-action: none; on all elements,
  • set width=device-width in the meta viewport tag.

Tried with Chromium 98 on desktop (mobile emulation in developer tools), as well as Chrome on Android. The same happens in Firefox 97 but only if I enable touch emulation. So I think it's according to spec, and not a browser issue.

Of course I can add some JavaScript to listen for touchstart or pointerdown events and add my own custom .active class. But I'd like to aim for a non-JavaScript solution if possible.

html

css

google-chrome

firefox

touch

0 Answers

Your Answer

Accepted video resources