Overview – Event Handling in JavaScript

Understanding Events in Javascript by The interaction of JavaScript with HTML is handled through events. Events are actions that occur when either the user or the browser itself manipulates the page.Some common events that occur with websites are page loads, button clicks, key presses, hovers, form submissions, window resizing, to name but a few. As developers, we can use these events to execute coded responses, such as displaying messages, validating data, reacting to button clicks, and really anything else we can imagine!

What is Actual Events in JS?

HTML events are “things” that happen to HTML elements.When JavaScript is used in HTML pages, JavaScript can “react” on these events.

What are Event Handlers & Event Listeners?

An event is fired whenever an action occurs on a page that JavaScript can react to, such as when a user clicks on a button (click event) or presses a key (keypress event).

An event handler is a JavaScript function that runs when an event fires.

An event listener attaches responsiveness to a given element, which allows the element to wait or “listen” for the given event to fire.

Events can be assigned to elements via inline event handlers, event handler properties & event listeners. Let’s take a look at each of these methods.

 

Inline Events

Let’s start with a basic example of an inline event handler. The below HTML consists of a button and a p element, we want the text content of p to change when the user clicks the button

				
					<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>Understanding Events</title>
</head>

<body>

<button onclick="changeText()">Click me</button>

<p>Change me!</p> <script data-no-optimize="1">var litespeed_vary=document.cookie.replace(/(?:(?:^|.*;\s*)_lscache_vary\s*\=\s*([^;]*).*$)|^.*$/,"");litespeed_vary||fetch("/wp-content/plugins/litespeed-cache/guest.vary.php",{method:"POST",cache:"no-cache",redirect:"follow"}).then(e=>e.json()).then(e=>{console.log(e),e.hasOwnProperty("reload")&&"yes"==e.reload&&(sessionStorage.setItem("litespeed_docref",document.referrer),window.location.reload(!0))});</script></body>
</html>
				
			

As you can see, we’ve added an attribute called onclick to our button element. The attribute value will be a JavaScript function we’ll create called changeText().

Event Listeners

Event listeners watch for an event on an element, instead of assigning the event directly to a property on the element, we’ll use the addEventListener() method to listen for the event.addEventListener() takes two mandatory parameters — the event to listen for and the listener callback function.The HTML for our event listener will remain the same as the previous example. And we’ll still be using the same changeText() function as before.However, we'll now attach the addEventListener()method to the button, as follows:.

				
					
// Function to modify the text content of the paragraph

const changeText = () => {
    const p = document.querySelector('p');
    p.textContent = "I changed because of an event listener.";
}

// Listen for click event

const button = document.querySelector('button');
button.addEventListener('click', changeText);
				
			

addEvenListner()

This is the modern way. This method allows to register as many handlers as we need, and it’s the most popular you will find:

 

				
					window.addEventListener('load', () => {
  //window loaded
})
				
			

Common Events

So far we’ve focused on using the click event while learning about inline event handlers, event handler properties and event listeners. However there are many more events available for us to work with, so let’s take a look!

Mouse Events

Mouse events are among the most frequently used events. They refer to events that involve clicking the mouse button or hovering and moving the pointer. And of course, these events also correspond to the equivalent action on a touch device. Some examples are:

click Fires when the mouse is pressed and released on an element.
dblclick Fires when an element is clicked twice.
mouseenter Fires when a pointer enters an element.
mouseleave Fires when a pointer leaves an element.
mousemove Fires every time a pointer moves inside an element.

click is actually a compound event that is comprised of combined mousedown and mouseup events, these fire when the mouse button is pressed down or lifted, respectively.

Using mouseenter and mouseleave together recreates a hover effect that lasts as long as a mouse pointer is on the element.

Form Events

Form events are actions that relate to forms, such as input elements and whether they are selected or unselected, and also form submission.

submit Fires when a form is submitted.
focus Fires when an element (such as an input) receives focus.
blur Fires when an element loses focus.

Focus is achieved when an element is selected, for example, through a mouse click or navigating to it via the TAB key.

JavaScript is often used to submit forms and send the values through to a back-end language. The advantage of using JavaScript to send forms is that it does not require a page reload to submit the form, and JavaScript can be used for form validation.

Keyboard Events

Keyboard events are used for handling keyboard actions, such as pressing a key, lifting a key, and holding down a key.

keydown Fires once when a key is pressed.
keyup Fires once when a key is released.
keypress Fires continuously while a key is pressed.

Although they look similar, keydown and keypress events do not access all the exact same keys. While keydown will acknowledge every key that is pressed, keypress will omit keys that do not produce a character, such as SHIFTALT, or DELETE

Learn from Instructor :

Join Our learning platform —

k2infocom—–click here

Need to learn other JavaScript topics:

Leave a Reply

Your email address will not be published. Required fields are marked *