Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does keypress() only fire when a textfield is focused in Firefox?

jQuery(document).ready(function ($) {
    $('body').keypress(function (e) {
        alert(e.which);
    });
});

This will pop up an alert when a key is pressed in Chrome but not in Firefox. However, if I create a text field and focus it, then press a key, an alert will pop up in Firefox. (Even though $('body') is still the jQuery object.)

How can I get the event to fire in Firefox even when a textfield is not focused? Is there a workaround? I will be firing an event when the Enter key is pressed anywhere on the page.

Thanks guys

like image 966
Nathan Avatar asked Dec 08 '25 12:12

Nathan


1 Answers

If you have no elements on the page, the browser might assume that the <body> element (or any of its descendants) doesn't have focus. Try binding your event to the document:

jQuery(document).ready(function ($) {
    $(document).keypress(function (e) {
        alert(e.which);
    });
});
like image 107
DarthJDG Avatar answered Dec 10 '25 02:12

DarthJDG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!