Yogesh Chauhan's Blog

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

in jQuery on January 14, 2021

Example

Explanation

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
How to make flexbox items of the same size?CSSHow to activate and deactivate hooks in a WordPress plugin?WordPressHow services and dependency injection work in Angular?AngularWordPress: How to set WP_SITEURL?WordPressCREATE DATABASE in PostgreSQLPostgresArray destructuring and Object destructuring in JavaScriptJavaScriptAdd animation to your skills bar using CSSCSSHow to use @supports rule in CSS?CSSSome Useful Operators in The SQL WHERE ClauseSQL/MySQLThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSSteps to Secure a VPNMiscellaneousHow to use data-* Attributes in HTML?HTML