Types of Events in JavaScript: Common Keyboard and Mouse Events
source link: https://code.tutsplus.com/articles/types-of-events-in-javascript-common-keyboard-and-mouse-events--cms-107243
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
JavaScript provides a wide range of events that allow you to interact with and respond to user actions on a webpage. Among these events, keyboard and mouse events are among the most commonly used. In this article, we will look at different kinds of keyboard and mouse events in JavaScript, and see examples of how to use them.
Keyboard Events
Keyboard events occur when a user interacts with the keyboard, such as pressing a key, releasing a key, or typing characters. Keyboard events let us do cool things like checking if a user has typed something correctly in a form or making certain actions happen when specific keys are pressed. It's like the website is listening to what keys you press and reacts accordingly. There are three types of keyboard events and they are:
The keydown
Event
This keyboard event is triggered when a user press down a key. It is repeatedly triggered if a user holds down a key.
document.addEventListener('keydown', function(event) { |
|
2 |
console.log('Key pressed is:', event.key); |
3 |
}); |
This code demonstrates how the keydown
event works. It adds an event listener to the document object's keydown
event. When a key on the keyboard is pressed, the specified function is executed. This function logs a message to the console. The message includes the string Key pressed is: followed by the value of event.key
, which represents the key that was pressed.
The keyup
Event
This keyboard event occurs when a key is released. It can be used to detect when a user releases a specific key.
document.addEventListener('keyup', (event) => { |
|
2 |
var name = event.key; |
3 |
alert(`Key pressed: ${name}`); |
4 |
}, false); |
The above code adds an event listener to the keyup
event such that when a key is released on the keyboard, it executes an arrow function. This arrow function assigns the value of event.key
to a variable called name and it represents the key that was released. An alert box appears when the key is released and it displays a message which includes the string Key pressed: followed by the value of the name variable using string interpolation (${name}
).
Another example that can be used to demonstrate the keyup
event is setting up an input field and creating a function that transforms characters typed into the input field into uppercase when the user releases a key. To try out the example below, create an input tag with an id of fname
and a function like thisonkeyup="myFunction()"
inside the input tag.
function myFunction() { |
|
2 |
let x = document.getElementById("fname"); |
3 |
x.value = x.value.toUpperCase(); |
4 |
} |
The keypress
Event
The keypress
event is triggered when a key is pressed. In the code sample below, an event listener is added to the document object that executes a function when a key is pressed and a character value is produced. The arrow function logs a message to the console of the browser which includes the string Key pressed: followed by the value of event.key
, which represents the character value of the pressed key.
document.addEventListener('keypress', (event) => { |
|
2 |
console.log('Key pressed:', event.key); |
3 |
}); |
It is important to note that some browsers no longer support the keypress
event and it is not fired for all keys (like Alt, Ctrl, Shift, or Esc) in all browsers. It is recommended to use the keydown
or keyup
events instead.
Example of Using the Keyboard Events
Mouse Events
Mouse events, on the other hand, help in the creation of more engaging websites. They handle events that occur when the mouse interacts with the HTML document such as clicking, moving, or scrolling. They enable us to react when users click mouse buttons, move their mouse over elements, or drag items around on the screen. It's as if the website is tracking your mouse movements and clicks to figure out what you want to do. There are various types of mouse events and they are:
The click
Event
This event is executed when a user clicks on an element.
var element = document.querySelector('.btn'); |
|
2 |
element.addEventListener('click', function () { |
3 |
element.style.backgroundColor = 'blue'; |
4 |
}); |
To execute the above code, create a button in HTML with a CSS class name of btn
. So what the above code does is that it selects the element with a CSS class name of btn
using the querySelector
method and assigns it to the element
variable. An event listener that listens for the click
event is added to the element. When the element is clicked, a specified function will be executed. In this case, the function is to change the background color of the element to blue.
You can also build a simple game where users get to click inside a box to continuously change the background color of the box by using the math.floor
and math.random
method to generate random colors.
The dbclick
Event
This event calls a function when a user double-clicks on an element with a mouse. To execute the code sample below, create a button in HTML with a CSS class name of btn
. Grab the element using the querySelector
method and add an event listener to it. When the button is double-clicked, the function is invoked, an alert message is displayed, and the font size of the text in the button increases.
var button = document.querySelector('.btn'); |
|
2 |
button.addEventListener('dblclick', function (event) { |
3 |
alert('Button double-clicked!'); |
4 |
button.style.fontSize = '40px'; |
5 |
}); |
An advanced way the dbclick
event can be used is to enable users to edit content. Double-clicking on a text element, for example, can convert it into an editable input field, allowing users to make changes directly. Below is a demo of editing content using the dbclick
event.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK