How to Use Event Listeners in JavaScript?

In this tutorial, I will show you How to Use Event Listeners in JavaScript.

How to Use Event Listeners in JavaScript?expoundsofttechsolution What is GMT?

You can listen to events on any element in the DOM. Javascript has an addEventListener() function that you can call on any element on a web page. The addEventListener() function is a method of the EventTarget interface. All objects that support events implement this interface. This includes windows, documents, and individual elements on the page.
An event listener is a process in JavaScript that waits for an event to occur. A simple example of an event is a user clicking the mouse or pressing a key on the keyboard.

Syntax:

How to Use Event Listeners in JavaScript?

element.addEventListener(event, listener, useCapture);

Parameters:

  1. Event: Event can be any valid JavaScript event. Events are used without an “on” prefix such as “click” instead of “onclick” or “mousedown” instead of “onmousedown”.
  2. Listener (Handler Function): This can be a JavaScript function that responds to the event.
  3. useCapture: This is an optional parameter used to control event propagation. A Boolean value is passed where “true” denotes the capturing phase and “false” denotes the bubbling phase.

JavaScript Code to show the working of addEventListener() method :

<!DOCTYPE html>
<html>

<body>
	<button id="try">Click here</button>
	<h1 id="text"></h1>
	<script>
	document.getElementById("try").addEventListener("click", function(){
	document.getElementById("text").innerText = "Ests";
});
	</script>
</body>

</html>

Output:

How to Use Event Listeners in JavaScript?

Hope this blog is helpful for you ,Thanks for reading this blog.

Hope this blog is helpful for you ,Thanks for reading this blog.

Hope this blog is helpful for you ,Thanks for reading this blog.