What is an event in web programming?
Events are actions that occur as a result of user interaction or system actions. Primarily, events represent the ways in which users can interact with the User Interface (UI), such as clicking, pressing keys, moving the mouse, and so on. For instance, when a user double-clicks on a button, the button is the HTML Element "target" that triggers the event. The "target" element is used as a reference to perform the consequences of the event, through a Handle Event Function. The HTML Element "target" is the UI component through which the user can make requests, such as posting or retrieving data from a form to a database.
The Document Object Model (DOM) is the representation of the HTML document as a tree-like structure. Through the document property, we can create or identify every HTML element in the DOM. With the DOM reference, we can set events on these elements, and the component that triggered the event will be the "target".
The "target" is a property that identifies the specific UI component that triggered the event. It is important to remember this concept, as the target property is used to determine which element initiated the event.
Event Target -> The HTML Node -> document
Events have already been categorized; we cannot invent them; these are attributes of HTML elements. The events are divided into categories that depend on the type of user action. It is essential to be aware of common HTML events, particularly those that begin with the prefix "on", which are special HTML attributes, here there are some examples:
Evento | Descripción |
---|---|
Form Events |
onblur: Fires the moment that the element loses focus onchange: Fires the moment when the value of the element is changed oncontextmenu: Script to be run when a context menu is triggered onfocus: Fires the moment when the element gets focus oninput: Script to be run when an element gets user input oninvalid: Script to be run when an element is invalid |
Keyboard Events |
onkeydown: Fires when a user is pressing a key onkeypress: Fires when a user presses a key onkeyup: Fires when a user releases a key |
Mouse Events |
onclick: Fires on a mouse click on the element ondblclick: Fires on a mouse double-click on the element onmousedown: Fires when a mouse button is pressed down on an element |
Drag Events |
ondrag: Script to be run when an element is dragged ondragend: Script to be run at the end of a drag operation ondragenter: Script to be run when an element has been dragged to a valid drop target ondragleave: Script to be run when an element leaves a valid drop target ondragover: Script to be run when an element is being dragged over a valid drop target |
Clipboard Events |
oncopy: Fires when the user copies the content of an element oncut: Fires when the user cuts the content of an element onpaste: Fires when the user pastes some content in an element |
Media Events |
onabort: Script to be run on abort oncanplay: Script to be run when a file is ready to start playing (when it has buffered enough to begin) oncanplaythrough: Script to be run when a file can be played all the way to the end without pausing for buffering oncuechange: Script to be run when the cue changes in a <track> element |
How can I turn a Component UI into an Event Target in JavaScript?
There are several ways to achieve this. In simple terms, choose the event and add them (how attribute) to the HTML Element "target" (hereinafter target) that triggers the event. Then assign it a Handle Event Function. Let’s explore some methods to accomplish this.
Assessing the event directly to a target element.
This practice is discouraged, however is a way, so let me explain it to you. Into your code HTML, add the event how an attribute to the target element. The event handler function must be assigned as a string type. However, you have to write code of the event handler function into JavaScript environment.
< body >
< button id="button-1" onclick="sayGreentingsHi()" >Hi< /button >
< script >
function sayGreentingsHi() {
alert('Hello')
}
< /script >
< /body >
Using this method, if you want to have access to the “event” object, you must pass it how parameter in the event handler function. Also, you can pass “this” which is a presentation of the current target that triggers the event. It is necessary to pass these parameters textually as “event” and “this”, don't for example “e”, you can do that into JavaScript environment. Pass these parameters may be convenient to if you want to use several times the same event handler function, how you can watch in the next example.
< body >
< button id="button-2" onclick="sayGreentings(event,this)" >Hi
< button id="button-3" onclick="sayGreentings(event,this)" >Bye
< script >
function sayGreentings(event, eleTarget) {
//Now I can use event.target.
// event.target is equal to eleTarget parameter
if(eleTarget === myTarget2) alert('Hello')
if(eleTarget === myTarget3) alert('Bye')
}
< /script >
< /body >
Target element calls addEventListener Method.
This is the best practice to set events. It procedure is pretty easy, first get the DOM reference of the HTML Element which you have selected how target. So, set it an id and you will have a CSS Selector Valid to identifier it. Then into a JavaScript environment the reference target must call the addEventListener Method, that waits for 3 parameters. This especial method is an Event handle will performance what should happen when the event has occurred.
The addEventListener(“type”, listener(), options) method takes three parameters:
Type: the type of event to listen for, written in string format. For example, “click”, “mouseover”, “keydown” ... Notice that the prefix “on” is not used as it is done in HTML attributes. Instead, the event name is used without the “on” prefix. For example, “click” instead of “onclick”.
Listener:The function that is to be executed when the event occurs. This function is known as “event handler” or “listener”. It can be an anonymous function or a named function.
Options (optional): An object that contains additional options for handling the event. The most common parameter is capture, which indicates whether the event should be handled in the capture phase (true) or in the bubble phase (false). The capture phase occurs when the event propagates upwards in the element tree, while the bubble phase occurs when the event propagates downwards.
< body >
< button id="myButton"> Hi
< script >
const button = document.getElementById("myButton");
button.addEventListener("click", function(){
alert("Hello!");
});
< /script >
< /body >
If you handle your events in this way, targeting each element individually, a problem can occur if one of them is his parent, which is the overlap of target events between parent and children elements. For example, if you set 2 targets, where one is the parent of the other, and you execute different actions for each, when you hover the mouse or click on the parent, the same action is triggered on its child as well. To avoid this behavior, you should use the event.stopPropagation() method. Let's look at the following example.
document.querySelector('.child').addEventListener('click', function(event) {
// Stop the event from bubbling up, just this element would be target
event.stopPropagation();
console.log('Clicked on the child element');
});
document.querySelector('.parent').addEventListener('click', function(event) {
console.log('Clicked on the parent element');
});
Here are some general guidelines on when to use event.stopPropagation():
1. When you want an event to be handled only by a specific element and not propagate to parent elements: In this case, you should call event.stopPropagation() in the event handler of the element you want to be the sole handler of the event.
2. When you want to prevent an event from propagating to sibling elements: If you have multiple sibling elements that handle the same event differently, you can call event.stopPropagation() in the event handler of each element to prevent the event from propagating to the others.
3. When you want to control the propagation of the event in a nested structure of elements: In this case, you can call event.stopPropagation() in the event handlers of the child elements, parent elements, or both, depending on how you want to control the propagation.
In the previous case, was the specific target who calls the addEventListener Method. However, the best practice is "event bubbling", it means assign the addEventListener Method to the “document”. So, when an event occurs on any element within the DOM, the event propagates up the element tree until an event handler is found to handle it.
To avoid confusion with the target, the event object that is passed as a parameter to the event handler is used, BDW you can simply name it as e, it is a convention to do so. The event object contains information about the event that occurred, including the element that originated it (event.target). The event handler can use this object to determine which element originated the event and make decisions accordingly.
document.addEventListener('click', function( event) {
// Using match() to identify the target by its class
if ( event.target. className.match('button')) {
console.log('Clicked on an element with the class "button"');
}
// Using event.target to identify the target by its nodeName
else if ( event.target.nodeName === 'BUTTON') {
console.log('Clicked on a button');
}
// Using event.target to identify the target by its class
else if ( event.target.classList.contains('link')) {
console.log('Clicked on an element with the class "link"');
}
// Using event.target to identify the target by its id
else if ( event.target.id === 'myElement') {
console.log('Clicked on an element with the id "myElement"');
}
//Check if the element that originated the event is the second child
else if (event.target.matches('#secondChild')) {
console.log('Clicked on the second child');
// Stop the event propagation
event.stopPropagation();
}
// Check if the element that originated the event is the third child
else if (event.target.matches('#thirdChild')) {
console.log('Clicked on the third child');
event.stopPropagation(); // Stop the event propagation
}
// If none of the above children were the target, ignore the event
else {
return;
}
});
The key points are:
1. The UI component needs to be the "target" of the event, meaning it is the element that triggers the event when the user interacts with it.
2. To make the UI component an event target, you need to associate an event handler function with it, typically by using the addEventListener() method or by setting an event attribute like onclick directly on the HTML element.
3. The event handler function is the "listener" that will respond to the event when it is triggered on the target component.