- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Keyboard Events
The keyboard events in JavaScript provide a way to interact with a web page or application based on the user's keyboard input. These events allow developers to capture and respond to various keyboard actions, such as key presses, key releases, and character inputs. The primary keyboard events in JavaScript include keydown, keypress, and keyup.
Common Keyboard Events
Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown event. This event equips developers with information about the specific key that was pressed: this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or Alt were also depressed.
Keypress Event − The keypress event triggers when a user types an actual character. Non-character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it to capture user input for form fields or create interactive typing features.
Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of a keyup event; this particular event proves beneficial in tracking specific keys' releases and subsequently implementing actions, thereby creating an interactive user experience.
Keyboard Event Properties
For keyboard events in JavaScript, several properties are commonly used to gather information about the key pressed. Here are some key properties specifically relevant to keyboard events −
Property | Description |
---|---|
event.key | String representing the key value of the pressed key. |
event.code | String representing the physical key on the keyboard. |
event.location | Integer indicating the location of the key on the keyboard. |
event.ctrlKey | Boolean indicating whether the Ctrl key was held down. |
event.shiftKey | Boolean indicating whether the Shift key was held down. |
event.altKey | Boolean indicating whether the Alt key was held down. |
event.metaKey | Boolean indicating whether the Meta (Command) key was held down. |
event.repeat | Boolean indicating whether the key event is a repeat event. |
event.isComposing | Boolean indicating whether the event is part of a composition of multiple keystrokes. |
event.which | Deprecated property; previously used to identify the numeric key code. |
event.getModifierState(keyArg) | Method that returns a boolean indicating whether the modifier key is pressed. |
Example: Keydown Event
This example illustrates the application of JavaScript's keydown event. The event listener seizes the keydown event upon pressing any key, displaying in an HTML element identified as "output" - its corresponding key (an event property).
<!DOCTYPE html> <html> <body> <h3>Press any key</h3> <script> document.addEventListener('keydown', function (event) { document.getElementById('output').innerHTML = "Key pressed: " + event.key; }); </script> <div id="output"></div> </body> </html>
Example: Keypress Event
In this example, the keypress event is utilized to capture a typed character. When a character is typed, the event listener triggers, and the character is displayed in the HTML element with the id "output".
<!DOCTYPE html> <html> <body> <h3>Type a character</h3> <div id="output"></div> <script> document.addEventListener('keypress', function (event) { document.getElementById('output').innerHTML = "Character pressed: " + event.key; }); </script> </body> </html>
Example: Keyup Event
The keyup event is showcased in this example. It captures the event when a key is released after being pressed. The released key is then displayed on screen.
<!DOCTYPE html> <html> <body> <h3>Press and Release a key</h3> <div id="output"></div> <script> document.addEventListener('keyup', function (event) { document.getElementById('output').innerHTML = "Key released: " + event.key; }); </script> </body> </html>
There is a difference between keydown and keypress. keydown is triggered when any key is pressed down, providing information about the pressed key, including modifiers. keypress is triggered specifically when a character key is pressed, providing information about the typed character without details on modifiers. Keydown fires continuously as long as the key is held down.
In all the above examples, we have used the addEventListener but these events can be listened to without this function as well. This is because of you can assign event handlers directly to specific properties. However, keep in mind that using addEventListener is generally considered a better practice because it allows you to attach multiple event handlers to the same event, and it separates JavaScript logic from the HTML structure.
Example: Without using addEventListener method
In this example, we have an input box. When it detects a keydown event (onkeydown), the handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the handleKeyUp function. Both the functions print appropriate messages to the screen.
<!DOCTYPE html> <html> <body> <div>Enter some text: <input onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)"> </div> <div id="output"></div> <script> function handleKeyDown(event) { document.getElementById('output').innerHTML+= "Key pressed: " + event.key+'<br>Key code: ' + event.keyCode+'<br>'; } function handleKeyUp(event) { document.getElementById('output').innerHTML+= "Key released: ' + event.key+'<br><br>"; } </script> </body> </html>