Search code examples
csspointer-eventsdisable

'disable' does not prevent 'onpointerup' event. Is there an 'onclick' equivalent using Pointer Events?


Using the 'disabled' css property does not prevent 'onpointerup' events from being handled by the associated function. What is the best way to achieve 'onclick' functionality (specifically that event handlers are not dispatched for 'onclick' when the element has the 'disabled' state) using Pointer Events?

I'm building a React application that uses Web Bluetooth (and learning a LOT along the way). Web Bluetooth needs an 'onpointerup' event to begin selecting devices and I was eager to use Pointer Events in the rest of the app for their portability across input devices.

I later found that I'd need to prevent the user from clicking a button and the cleanest way to do this is with the 'disable' tag. After hours of diving into React and styled-components (and actually when I started writing this question) it struck me -- of course 'onpointerup' still applies to a 'disabled' element (because the pointer still was on it and lifted up...)

Here's a bare-bones html example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Example</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>function something(){ console.log('something happened');}</script>

    <div>
      <!-- This is what I wanted to use... -->
      <button           onpointerup="something()">Do Something onpointerup</button>
      <button disabled  onpointerup="something()">Do Something onpointerup</button>
    </div>

    </div>
      <!-- But this is what I found to work... -->
      <button           onclick="something()">Do Something onclick</button>
      <button disabled  onclick="something()">Do Something onclick</button>
    </div>
  </body>
</html>

Well the results are (now) all expected. The only element that does not make something happen is the disabled button that uses 'onclick'.

So...

  1. Is there a good way to get the "disabled 'onclick'" functionality using Pointer Events?
  2. Is 'onclick' so ubiquitous that it's not worth the trouble to standardize on Pointer Events?

Thanks all!


Solution

  • I think the CSS pointer-events property could work for you.

    html

    <button class="mybutton">
    

    CSS

    .disablePointerEvents {
        pointer-events: none;
    }
    

    JS

    document.querySelector(".myButton").classList.toggle("disablePointerEvents");
    

    From the MDN documentation, with the none value : "The element is never the target of pointer events"