Saturday, June 17, 2023

Types of Events in JavaScript: Common Keyboard and Mouse Events

Types of Events in JavaScript: Common Keyboard and Mouse Events

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.

1
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.

1
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 this onkeyup="myFunction()" inside the input tag.

1
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.

1
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.

1
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.

1
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.

 The mouseup and mousedown Events

This mousedown event is triggered when a user presses down on a mouse button when the cursor is over an element. Create a button with an id of text. When the button is clicked with a mouse, it alerts a message "Mouse button pressed".

1
var button = document.getElementById('text');
2
button.addEventListener('mousedown', function (event) {
3
  alert('Mouse button pressed!');
4
});

Whereas the mouseup event is triggered when the user releases the mouse button after clicking on an element. Create a button with an id of text. When the button is clicked with a mouse and released, it alerts a message Mouse button released.

1
var button = document.getElementById('text');
2
button.addEventListener('mouseup', function (event) {
3
  alert('Mouse button released!');
4
});

A practical example of how these mouseup and mousedown events can be used is when implementing a drag-and-drop functionality, and for drawing and sketching.

The mouseover and mouseout Event

The mouseover event occurs when the mouse pointer hovers over an element, while the mouseout event occurs when the mouse pointer leaves the element. Here's a quick demo of these two  mouse events.

In the above demo, the image is enlarged when a user's mouse goes over the image and it returns to its normal size when the mouse leaves the image.

The mouseover event can be used to create a tooltip that provides additional information about an element when it is hovered over. The mouseover and mouseout events can also be used to create interactive navigation menus such that when the user's mouse pointer hovers over a menu item, it can cause submenus to appear.

The mousemove and mouseleave Events

The mousemove event is triggered when the user moves the mouse cursor over an element, and the mouseleave event is triggered when the mouse cursor leaves the element. These events enable developers to monitor mouse movements.

The above code gets the mouse pointer coordinates whenever a user's mouse is inside the div container and it displays the coordinates values in a text underneath the box. It then displays another text indicating that the pointer has left the div after the user's mouse leaves the div element.

Conclusion

Keyboard events such as keydown, keyup, and keypress allow us to capture and respond to user input from the keyboard. Keyboard events are essential for user interaction, whether you're implementing form validation, providing keyboard shortcuts, or creating text-based games. Mouse events, on the other hand, such as click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, and mouseleave, allow us to capture and respond to user interactions with the mouse.

In conclusion, JavaScript's keyboard and mouse events enable us to build websites that appear to be listening and responding to our activities by capturing the keys that are pressed and the mouse's movements. Now that you've learned about the various types of keyboard and mouse events and how they can be used to build interactive websites and web applications, go ahead and build fun and interactive games and websites. Happy Coding!


No comments:

Post a Comment