A quick introduction to JavaScript DOM events

A quick introduction to JavaScript DOM events

what is an event?

An event is an action that occurs in the web browser. When the page loads, it is called an event. When the user clicks a button, that click too is an event.

Event handler

an event handler is a piece of code that will execute to respond to an event. An event handler is also known as an event listener.

There are three ways to assign event handlers.

  1. HTML event handler attributes
  2. DOM level 0 event handlers
  3. DOM level 2 event handlers

now let's go all of them one by one :)

HTML event handler attributes

The simplest way to assign an event handler is to add them directly to the start tag of the HTML elements using the special event-handler attributes :

For example, to assign a click handler for a button element, we can use onclick attribute :


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>events</title>
</head>
<body>

    <button onclick="alert('you clicked Me')">click me</button>

</body>
</html>

Disadvantages of Html event handler attributes :

Assigning event handlers using HTML event handler attributes are considered as bad practices and should be avoided as much as possible because of the following reasons:

First, the event handler code is mixed with the HTML code, which will make the code more difficult to read.

second, time-consuming. you cant have two onclick event handlers and end up adding one event for each element with on* style events.

DOM level 0 event handlers

To assign an event handler, you set the onclick property to a function.

example :

let btn = document.querySelector('#btn');

btn.onclick = function() {
    alert('Clicked!');
}; // output : Clicked

DOM level 2 event handlers

Another way to add an event to any object in javascript is by using addEventListener().

Example :


<!DOCTYPE html> 
<html> 
<body> 

<button id="demoButton">events</button> 

<script>

 document.getElementById("demoButton").addEventListener("click", function(){ alert("hello world"); 

}); //hello world


</script>

 </body> 

</html>

conclusion

this article was about events in javascript

PS: the best way to add an event in javascript is by using addEventlistener :)

That's all, thanks for reading, and have a great day! :)