Home »
JavaScript
Event Listeners in DOM
Here, we are going to learn about the event listeners in DOM (Document Model Element) with examples.
Submitted by Siddhant Verma, on October 25, 2019
Event Listeners in DOM
To implement complex functionalities for a dynamic web application, event listeners are used instead of just directly attaching events to the DOM elements. JavaScript developers mostly stay away from markups. For example, a developer working on a project would rarely ever look at the HTML. In those scenarios, event listeners are extensively used since you can directly attach an event listener to any DOM element from the script. In this article, we'll see how to add event listeners to DOM elements using JavaScript.
Add event listeners to any DOM object
You can add event listeners to any DOM object. This means that the DOM object need not necessarily be a DOM element, you can also add event listeners to the window object. We add event listeners to an element using the addEventListener() method.
The general syntax for attaching event listeners is,
element.addEventListener(event type, callback function);
We first grab an HTML element by querying the DOM and attach the addEventListener() method onto it. This method takes three parameters, however, we'll only look at the essential two. The first one is the type of event, ex click, focus, submit, etc and the second parameter is a callback function that will fire once the event is triggered.
The addEventListener() method allows us to attach as many event listeners as we want to as many DOM elements we want. This means that you can attach the same event listeners to multiple elements or multiple event listeners to the same element.
Example of attaching an event listener to a DOM element
Let's see a simple example of attaching an event listener to a DOM element.
Create an index.html file with the following starter template,
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Events in DOM</title>
</head>
<body>
<h1>Event Listeners</h1>
<hr>
<hr>
<div class="container">
<p>This button will trigger an alert </p>
<button>Click me!</button>
</div>
</body>
<script>
const btn = document.querySelector('button');
btn.addEventListener('click', () => {
alert('This button was clicked!');
})
</script>
</html>
Copy some basic styles to the styles.css file,
body {
background: mintcream;
}
h1 {
padding: 20px 20px;
margin: 10px auto;
text-align: center;
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
p {
padding: 10px 10px;
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
color: chocolate;
font-size: 22px;
}
.container {
text-align: center;
}
button {
padding: 10px;
background: violet;
color: white;
border: 2px solid salmon;
border-radius: 6px;
cursor: pointer;
}
Output
We will display an alert() on clicking the button so we need to attach an event listener to our button object.
<script>
const btn = document.querySelector('button');
btn.addEventListener('click', () => {
alert('This button was clicked!');
})
</script>
Output
You can also remove an event listener using the removeEventListener() method.
Let's remove the event listener now. For that, we need to create a separate function in which we can then call our alert() and pass that function invocation as the second parameter in our event handler.
<script>
const btn=document.querySelector('button');
btn.addEventListener('click',showAlert());
function showAlert(){
alert('This button was clicked!');
}
btn.removeEventListener('click',showAlert());
</script>
Now we no longer get an alert on clicking the button.
This way we can easily attach event listeners to DOM elements.
Let's see another example of how we can add an event listener to the window object.
Add another <div> in the index.html. We'll append some lorem ipsum in this <div> on resizing the browser.
<div class="para">
</div>
Now let's get a reference to this <div>,
const para=document.querySelector('.para');
We'll attach an event listener of type resize to the window object and inside we'll add a template string with some lorem ipsum embedded in a <p>.
const para=document.querySelector('.para');
window.addEventListener('resize',()=>{
para.innerHTML='<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro illum aut tenetur, laudantium dolor quo recusandae et doloremque esse sit impedit soluta eligendi quibusdam dolores enim magni tempore, eius velit.</p>'
})
You can see now that on resizing your browser you get some lorem ipsum on the page.
Output