How to Attach Event to HTML Element in JavaScript

JavaScript is all about making HTML manipulative and interactive. Using JavaScript Events we can know if end user is interacting with page or not. If user is interacting with page then using events we can take appropriate actions.

Let’s look at how we can attach basic event to HTML or DOM elements.

Suppose, when user clicks on HTML button you want to show message. To achieve this, you first have to attach click event to the Button element and that click event will call function defined by you to show the message.

There are two common ways to attach event to the elements.

1. Using Element Attributes

Attributes are extension to the HTML elements. They provide extra functionality to the elements.

Example:

‎
<!DOCTYPE html>
<html>
	<head>
	 Button Click Example
	</head>
	<body>
		 
		<p>
		  <button  id ="btn" onclick="btnClick();"> Click Button </button>
		</p>

		<script>
		 function btnClick(){
		  alert('Hello Button');
		 }
		</script>
		
	</body>
</html>
‎

In the above example you can see we have added onclick event attribute to the button element. Also, we have created function btnclick which is going to display alert. We have called this function with onclick attribute.

Run above code in the browser and click on the button to see message in the alert.

2. Using addEventListener

There are lots of standard and event attributes you can use with a element. If you want to use multiple event attributes on single element then it would not be feasible or a good idea to add those in a element. It will not be good for readability and maintenance.

In this case, you can just use addEventListener function to attach an event attribute to an element without adding attribute to the element directly.

Let’s see above example using addEventListener.

Example:

‎
<!DOCTYPE html>
<html>
	<head>
	 Button Click Example
	</head>
	<body>
		 
		<p>
		  <button id ="btn2">Click Button</button>
		</p>

		<script>
		   const button = document.getElementById("btn2");

		   button.addEventListener('click', function () {

		    alert("Hello Button");

		   });
		</script>
		
	</body>
</html>
‎

In the above example, we have not added onclick event attribute to the button element in the HTML. But, in the JavaScript code you can see that we are retrieving button object through its id (btn2). Then, we are adding click event to the button using addEventListener.

Basically, addEventListener takes two parameters, first is an event name and second is a function which will do the action.

Run above code and you will see the same results as first example.

Categories js