Yogesh Chauhan's Blog

How to catch .keypress() on body using jQuery?

in jQuery on January 14, 2021



keypress() binds an event handler to the “keypress” event. It can also trigger that event on any element.

When the browser records keyboard input, the keypress event is sent to an element.

It is similar to the keydown event, except that some keys like modifier and non-printing keys (Shift, Esc, delete) trigger keydown events but they cannot trigger keypress events.

We can attach keypress event handler to any element, but the event is only sent to the element with focus.

All browsers use different properties to store this information. So, jQuery normalizes the .which property so we can reliably use it to retrieve the character code.

While keydown and keyup provide a code that indicates which key is pressed, the keypress provides info on which character was entered.

For example, keydown and keyup indicates 65 when we press a lowercase “a”, but keypress will indicate it as 97.

Interestingly, all events reports 65 for an uppercase “A”.

That’s why .keydown() or .keyup() is a better choice when catching special keystrokes such as arrow keys, .

Learn more about it on Official Docs.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
What is ECMAScript?JavaScriptHow to activate and deactivate hooks in a WordPress plugin?WordPress4 ways to create Date Objects in JavaScriptJavaScriptCSS Overflow Property with ExamplesCSSHow to Hide HTML elements automatically after few seconds using JavaScript?HTMLHow to Install Xcode Command Line Tools on MacOS?MiscellaneousHow to enable and disable button using JavaScript?JavaScriptHow to display a student’s individual transcript in Colleague?ColleagueHow to display modal from bottom to top using CSS and JavaScript?CSSHow to control file extensions with an .htaccess file?MiscellaneousHow to uninstall Cocoapods from the Mac OS?MiscellaneousWordPress: How to set WP_SITEURL?WordPress