Page Content

Posts

How to Use Events in JavaScript Development

Events in JavaScript

Events in JavaScript web development are basic events that a web browser will alert your program about. Because they enable the website to react to user activities and changes in the browser’s state, these events provide web pages their dynamic and interactive qualities.

The two primary categories of events are browser/document actions and user interactions.

The individual utilising the webpage initiates User Interaction Events. These consist of a broad range of behaviours:

  • Mouse Events: Clicking a button or link, pressing or releasing a mouse button, moving the mouse pointer, or moving across or away from an element. Mouse wheel rotations and double clicks are mouse events.
  • Keyboard Events: Keydown, keyup, and character generation.
  • Form Events: Form events are interactions with buttons or input fields on a form. Examples of this are when an element’s value changes (change), when it acquires focus on the keyboard (focus), when it loses focus (blur), or when a form is submitted (submit). Another is that when text is entered, the input event is triggered more often than the change.
  • Drag and Drop Events: Dragstart, drag, dragend, dragenter, dragleave, dragover, and drop are actions associated with dragging elements.
  • Touch Events: For touchscreen gadgets (touchend, touchstart, and touchmove).

Regardless of particular user element interactions, changes to the document or the browser window itself cause Browser and Document Action Events to be triggered:

  • Loading Events: These include when the page loads everything (load), when the original HTML document is entirely parsed but resources like images may still be loading (DOMContentLoaded), or when you navigate away from the page (unload, beforeunload, pagehide). The loading status of documents is likewise connected to the readystatechange event.
  • Window Events: Browser window events include scrolling (scroll) and resizing (resize). Additionally, a window may blur or gain focus.
  • Network/State Changes: For example, a loading issue or a shift in network connectivity (online, offline).
  • History Navigation: Using the Back or Forward buttons to navigate the user’s browser history triggers the popstate event.

Responding to Events: Event handlers and event listeners are functions that are registered to run when a specific event occurs on a specific element or object (the event target). JavaScript uses these functions to respond to events.

Three primary methods exist for registering these handlers:

  • HTML attributes: Including characteristics like onclick=”myFunction()” straight within the HTML element is known as HTML attributes. Although this is simple to comprehend, you are only allowed to use one handler per event type, and it is not readily adjustable dynamically. In general, it’s not the best approach for production code.
  • DOM element properties: In JavaScript, you may assign a function to attributes like element.onclick = myFunction;. The event name is often followed by “on” at the beginning of these properties.
  • addEventListener(): AddEventListener() is the contemporary method of choice. The addEventListener() method lets you connect several handlers of the same kind to the same target. It may be used on elements, documents, and windows. It accepts as inputs the handler code and the event type (such as “click”) as a string. IE8 and previous used an older technique called attachEvent().

Invocations of event handlers often receive event objects. Important event details are contained in this item. An event is identified by a string in the object’s type property (such as “click” or “mousedown”), and the element or object on which the event took place is specified by the target property. IE8 and below utilise srcElement rather than target. The event object also includes methods like stopPropagation() to stop the event from “bubbling” up the DOM tree to parent elements and preventDefault() to stop the browser’s default action linked to the event (to stop a form from submitting or a link from navigating, for example). In many cases, events “bubble” up the document tree from the target element to its ancestors.

Let’s examine some typical kinds of events:

click: This event is frequently utilised. Activating an element by pressing and releasing a mouse button over it or by other means (such as tapping on touch devices or using the Enter key or spacebar) triggers this higher-level event. Both mousedown and mouseup events precede the click event. The input event is independent of the device. Click events on links can be stopped by using preventDefault(). By default, click events follow the link. The document tree bubbles up when you click events.

mouseover: When the mouse cursor lands on an element or one of its children, this event is triggered. A mouse event has occurred. If you simply want to know when the pointer enters the element itself and not its children, some mouseover events, like click, can be difficult. An alternative to bubbling is the mouseenter event.

submit: The submission of a form triggers this action. This event is a form. On the actual <form> element, the event is triggered. PreventDefault() can be used to stop a form’s default action of submission. AddEventListener’s “submit” event type or the onsubmit property can be used to attach handlers.

load: This event is triggered on the Window object upon the full loading and display of the document along with all of its external resources, including images. This crucial event makes sure that all DOM material is accessible before scripts attempt to access or modify it, which is why it’s frequently used to enclose other functionality.

Form related events (change, focus, blur, input, reset, select), mouse events (mousedown, mouseup, dblclick, mousemove, mouseout, mousewheel, mouseenter, mouseleave), and drag and drop events. Additionally, there are events for changing the state of the browser (resize, scroll, error, unload, beforeunload, popstate, online, offline, visibilitychange) and touch events for touchscreens (touchstart, touchmove, touchend).

Here is a code example demonstrating handling DOMContentLoaded, load, click, and mouseover/mouseout events using addEventListener:

<!DOCTYPE html>
<html>
<head>
<title>Common Events Example</title>
<style>
#hoverArea {
width: 100px;
height: 50px;
background-color: lightblue;
margin: 10px 0;
text-align: center;
line-height: 50px;
cursor: pointer;
}
</style>
</head>
<body>

<button id=”myButton”>Click Me</button>
<div id=”hoverArea”>Hover Over Me</div>
<p id=”status”>Script loading…</p>

<script>
// Log that the script started parsing.
console.log(‘Script started parsing.’);

// **Browser Event: DOMContentLoaded**
// Fires when the initial HTML document is fully loaded and parsed.
// Occurs on the document object.
// This is a good place to start accessing/manipulating DOM elements.
document.addEventListener(‘DOMContentLoaded’, function(event) {
console.log(‘DOMContentLoaded event fired on:’, event.target); // event.target is the document
const statusElement = document.getElementById(‘status’);
const myButton = document.getElementById(‘myButton’);
const hoverArea = document.getElementById(‘hoverArea’);

if (statusElement) {
statusElement.textContent = ‘Document ready. Waiting for interactions.’;
}

// **User Event: click**
// Attaching a ‘click’ event listener to the button using addEventListener.
// addEventListener is the preferred method.
if (myButton) {
myButton.addEventListener(‘click’, function(event) { // Receives the event object
console.log(‘Click event fired!’);
console.log(‘Event Type:’, event.type); // event.type gives the event name
console.log(‘Event Target:’, event.target); // event.target gives the element that fired the event

if (statusElement) {
statusElement.textContent = `Button clicked (${event.target.tagName}).`;
}
// Example of preventing default (though less relevant for a button’s click):
// event.preventDefault(); // Prevents the default browser action
});
} else {
console.error(“Button element not found!”);
}

// **User Events: mouseover and mouseout**
// Attaching listeners to the hover area.
if (hoverArea) {
hoverArea.addEventListener(‘mouseover’, function(event) {
console.log(‘Mouseover event fired on:’, event.target);
if (statusElement) {
statusElement.textContent = ‘Mouse is over the area.’;
}
});

hoverArea.addEventListener(‘mouseout’, function(event) {
console.log(‘Mouseout event fired on:’, event.target);
if (statusElement) {
statusElement.textContent = ‘Mouse left the area.’;
}
});
} else {
console.error(“Hover area element not found!”);
}

// Note: Form ‘submit’ events are typically attached to the <form> element itself.
// Example (assuming a form with id=”myForm”):
// const myForm = document.getElementById(‘myForm’);
// if (myForm) {
// myForm.addEventListener(‘submit’, function(event) {
// console.log(‘Form submit event fired!’);
// event.preventDefault(); // Often used to handle submission via JavaScript
// });
// }
});

// **Browser Event: load**
// Fires when the entire page, including all resources (images, etc.), is fully loaded.
// Occurs on the window object.
window.addEventListener(‘load’, function(event) {
console.log(‘Window load event fired on:’, event.target); // event.target is the window
const statusElement = document.getElementById(‘status’);
if (statusElement) {
statusElement.textContent += ‘ Page fully loaded.’;
}
});

</script>

</body>
</html>

The usage of addEventListener in JavaScript to register methods that react to standard browser (DOMContentLoaded, load) and user interaction (click, mouseover, mouseout) events is demonstrated in this example. The event object also offers details about the event that occurred. The foundation of creating dynamic and interactive websites is an understanding of and skill with events.