Home > Mobile >  Disabling a button block key events on firefox
Disabling a button block key events on firefox

Time:09-26

I have a simple button. When the user click the button I want to disable the button and to register some key events.

Here is a simple example :

<!DOCTYPE html>
<html>
<body>
    <button>Click me</button>
    <script>
        button = document.querySelector('button');
        button.addEventListener('click', ()=>{
            button.disabled = true;
            document.addEventListener('keydown', ()=>{
                alert('Key down')
            });
        });
    </script>
</body>
</html>

On firefox when i run this code :

  1. I load the page
  2. I click the button
  3. I try to hit a key and nothing happens
  4. I cick anywhere on the page
  5. I try again to hit a key and the alert box shows up

I don't understand why the user have to click somewhere on the page to "activate" the key events. This is not the case if i don't disable the button.

I've tried to give focus to another element. Like adding document.body.focus(); to the click event and it doesn't helps.

P.S: This is a minimal example in pure js but in my project I'm using Vue.js to disable the button and to fire the click event (<button @click='activateKeyEvents' :disabled='keyEventsAreActivated'/>). So the ideal solution for me would be a solution that does not rely on the order in which I perform the tasks. Because in practice I have no control over this order.

CodePudding user response:

you should remove focus from button too.

<button>Click me</button>
    <script>
        button = document.querySelector('button');
        button.addEventListener('click', ()=>{
            button.disabled = true;
            console.log('btn event loaded...');
            window.focus();
            if (document.activeElement) {
              document.activeElement.blur();
            }
            document.addEventListener('keydown', ()=>{
                console.log('keydown event loaded...');
                alert('Key down')
            });
        });

have fun :)

CodePudding user response:

That is because the element receiving the keyboard event should be interactive, to make document.body a such, the tabindex attribute should be added to it:

<!DOCTYPE html>
<html>
<body>
    <script>
      document.addEventListener('keydown', ()=>{
          alert('Key down')
      });
      setTimeout(() => {
        document.body.setAttribute('tabindex', -1);
        document.body.focus();
      }, 1000);
    </script>
</body>
</html>

  • Related