Explain about EventHandler with Examples in JavaScript


JavaScript Events, Are you familiar with them? Any action that occurs when we interact with a website is a JavaScript event. These actions include hitting a key on the keyboard, selecting an option in a select box, moving the mouse cursor, and so on. A JavaScript event handler is a function that is called when any of these events fires.

In this article, we are going to talk about event handlers, their implementation, and its components with various coded examples.

Events

You may create JavaScript code that responds to certain conditions using events.

Events that come to mind are −

  • Pressing a key

  • Webpage loading finished

  • Clicking a link on the web-page

What are Event Handlers?

JavaScript gives us event handlers so we may execute our pieces of code when certain events take place. Every event handler in JavaScript begins with the word on and deals with a particular kind of event.

Implementing an Event Handler

To implement an event handler, we typically include the event handler name inside the HTML element of the object we wish to manipulate, followed by the phrase "SomeJSCode," where SomeJSCode denotes the JavaScript code we want to execute when the event fires.

Example

<html>
<body>
   <input type="submit" name="IamHere" value="Hey there!" onclick="alert('Welcome!')"/>
</body>
</html>

If we want our markup(HTML) to adhere to the XHTML specification, we should use all lowercase letters in the HTML text instead of capital letters like the original JS event handler ("onClick"). Names of every element and attribute must be in lowercase in XHTML.

Managing Events

Various ways for Javascript to handle an event There are three methods for managing events, or you might say three different kinds of event handlers.

  • Using addEventListener to handle

  • using the object method for handling

  • Using the HTML inline property to handle

Using addEventListener

The ideal approach to handle an event is using addEventListener since removeEventListener allows you to get rid of the related handlers.

The listener mentioned above comes in two varieties.

  • Capture − Here, the parent of the element takes precedence over the one in which the event occurs.

  • Bubble − In this case, the actual element where the event occurs is given precedence over its parent.

Syntax

document.addEventListener("click me", function(){
   document.getElementById("example").innerHTML = "Hello Tutorials Point!!";
});

Example

Let’s have an example of addEventListner.

<html>
<body>
   <p>Click anywhere on the page to print "Hello tutorials point!".</p>
   <p id="eg"></p>
   <script>
      document.addEventListener("click", myFunction);
      function myFunction() {
         document.getElementById("eg").innerHTML = "Hello tutorials point!";
      }
   </script>
</body>
</html>

Using an object method

Every element in the DOM has a method that may be used to handle events, such as onclick, ondrag, and onkeypress. This method allows you to pass a function that accepts the event object as an argument.

Syntax

objectName.methodName()

Example

Let’s have an example of accessing object methods.

<html>
<body>
   <h2>JS Objects</h2>
   <p id="example"></p>
   <script>
      const person = {
         fName: "Tutorials",
         lName: "Point",
         id: 1111,
         fn: function() {
            return this.fName + " " + this.lName;
         }
      };
      document.getElementById("example").innerHTML = person.fn();
   </script>
</body>
</html>

Using the HTML inline property

Events may also be handled using an HTML inline property thanks to the HTML syntax.

Function calls are accepted as values for these properties.

The callback parameter for the event handlers is an event object that contains information about the event.

Syntax

<html_element event_handler="event_function()">Text</html_element>

Example

Let’s have an example.

<html>
<body>
   <h1>The Window Object</h1>
   <h2>The alert() Method</h2>
   <p>Click the button to display an alert box.</p>
   <button onclick="myFunction()">Try it</button>
   <script>
      function myFunction() {
         alert("Hello! I am an alert box!");
      }
   </script>
</body>
</html>

The Event Component

When an event takes place, the Event object is automatically generated. To get more details about the event, you may query a number of the attributes connected to the Event object −

  • Event.data − The onDragDrop event uses this. returns a list of dropped object URLs in an array.

  • Event.height − Event.height contains the height of the frame that has the event-related object stored in the event.height variable.

  • Event.modifiers − It returns a string having a list of modifier keys pressed during a keystroke or mouse movement. Control_mask, Alt_mask, Meta_mask, and Shift_mask are the settings for the modifier keys.

  • Event.pageX and Event.pageY − When an event fires, these contain the (X,Y) coordinates of the pointer relative to the page.

  • Event.screenX and Event.screenY − The (X,Y) pixel coordinates of the pointer on the screen at the moment of the event are stored in these attributes.

  • Event.target − Event.target gives back a string identifying the event's initiating object.

  • Event.type − Event.type provides a string representation of the event type (keypress, click, etc).

  • Event.which − This event component returns a number which represents the mouse buttons.Left click =1Right click=2Middle click=3

  • Event.width − This event component has the stored properties of the frame width connected with the happening event.

  • Event.x and Event.y −These attributes store (X,Y) pixel coordinates of the cursor concerning the layer associated with the event.

Several Typical Event Handlers

Let's take a closer look at a couple of the most popular event handlers and consider their potential applications.

onChange event

onChange is frequently used to carry out an action when a value has been changed by the user in a field, validate form fields, or both. When a user updates a field and then clicks elsewhere on the screen or presses the TAB key, the event handler is activated (i.e. the object loses focus).

Example

<html>
<body>
   <p>Select a state name from the list.</p>
   <select id="selectMe" onchange="myFn()">
      <option value="Bihar">Bihar</option>
      <option value="UP">UP</option>
      <option value="Delhi">Delhi</option>
      <option value="Punjab">Punjab</option>
   </select>
   <p>On selecting a new state name, a function is triggered which have O/P value as selected state name.</p>
   <p id="example"></p>
   <script>
      function myFn() {
         var x = document.getElementById("selectMe").value;
         document.getElementById("example").innerHTML = "Choosen state name: " + x;
      }
   </script>
</body>
</html>

onClick event

When a user clicks the target object with the mouse, the onClick handler is activated. It's a terrific approach to make dynamic Web sites based on JavaScript since we can use it on a variety of items, like buttons, checkboxes and links.

Example

<!DOCTYPE html>
<html>
<body>
   <h2>onclick Event</h2>
   <button onclick="myFn()">Click me</button>
   <p id="example"></p>
   <script>
      function myFn() {
         document.getElementById("example").innerHTML = "You are at tutorials point";
      }
   </script>
</body>
</html>

onFocus event

when the given object acquires focus, onFocus is launched. This often occurs when the user uses the mouse button to click on the object or the TAB key to move their cursor over it. Most form components may be utilised with onFocus.

Example

<html>
<body>
   <h2>The focus Event</h2>
   Type something to observe onFocus event: <input type="text" onfocus="myFn(this)">
   <script>
      function myFn(m) {
         m.style.background = "red";
      }
   </script>
</body>
</html>

onKeyPress event

When a user presses a key(on the keyboard), the "onkeypress" event fires.

The following is the sequence of events associated to the “onkeypress” event −

  • onkeydown

  • onkeypress

  • onkeyup

Example

<html>
<body>
   <p>On KeyPress event</p>
   <input type="text" onkeypress="myFn()">
   <script>
      function myFn() {
         alert("A key is pressed");
      }
   </script>
</body>
</html>

onLoad

When the page has fully loaded, the onLoad handler is called. The dreaded pop-up advertisement windows and starting additional operations like animations or timers after the entire page has completed loading are frequent applications of the onLoad function.

Example

<html>
<body onload="myFn()">
   <h1>You are at the tutorials point!!</h1>
   <script>
      function myFn() {
         alert("Webpage Loaded!");
      }
   </script>
</body>
</html>

mouseover and mouseout events

When the mouse cursor moves out of an element, the “onmouseout” event fires.

Onmouseout is frequently used in combination with the “onmouseover” event, which occurs when the pointer is moved over an element.

Example

<html>
<body>
   <h1 id="example" onmouseover="mouseOverme()" onmouseout="mouseOutOfMe()">Mouse over and out</h1>
   <script>
      function mouseOverme() {
         document.getElementById("example").style.color = "red";
      }
      function mouseOutOfMe() {
         document.getElementById("example").style.color = "blue";
      }
   </script>
</body>
</html>

onSubmit event

Before the form is submitted to the server, it is frequently validated using the “onSubmit” event handler, that is compatible only with the Form object. Form validation using JavaScript is a lesson we have on the subject in its entirety.

Example

<html>
<head>
   <title>Welcome To My Domain</title>
</head>
<body>
   <form onsubmit="alert('Form Submitted!!')">
      UserName:<input type="text" name="user"><br/>
      College:<input type="text" name="colg"><br/>
      City:<input type="text" name="city"><br/>
      Mobile:<input type="text" name="mob"><br/>
      <input type="submit" value="SUBMIT">
   </form>
</body>
</html>

Conclusion

In this article, we learned event handling, their implementation, managing events and its components with various coded examples of several event handlers.

Updated on: 19-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements