简体   繁体   中英

jQuery keydown event handling trouble in Mozilla Firefox

Keydown on body-element event stops firing after disabling button-element by it's click event handler.

Actions sequence:

  • keydown is firing

  • click on button

  • keydown stops firing

  • click on body

  • keydown starts firing again

Notice: This behavior only occurs in mozilla firefox. In google chrome it works as it should.

 $(document).ready(function(){ $('body').keydown(function () { console.log('<body> keydown'); }); $('#button').click(function () { this.disabled = true; }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Button</button>

It is because of browser's behaviour, in Chrome when the button is clicked browser will automatically focus out from the button and focus on body. However, Firefox doesn't exhibit this behaviour, it just does nothing when the button is disabled and focusing on same element ie button. But in case when it is not disabled it will focus on body.

From the Clicking and focus of Button Element

Whether clicking on a <button> causes it to (by default) become focused varies by browser and OS.

For its working you have to use .blur() on button like,

 $(document).ready(function() { $('body').keydown(function() { console.log('<body> keydown'); }); $('#button').click(function() { this.disabled=true; $(this).blur(); }); });
 .disabled { border: 1px solid #999999; background-color: #cccccc; color: #666666; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Button</button>

After you click the button you're leaving focus on the button, which is killing and keydown events.

What if you add this.blur() after the this.disabled = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM