Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Adding Event Listeners to HTML Elements | DOM Event Handling and Forms
HTML & JavaScript Interactivity for Beginners

book
Adding Event Listeners to HTML Elements

In the previous chapter, you saw how events trigger function calls through event attributes inside an HTML element. However, that method has many drawbacks. If an element had multiple events, putting all the event attributes to handle each of them inside an HTML tag makes the code look bloated and unreadable.

Therefore a better way around this issue is to keep the functionality separate from the structure. Thus it would help if you add an event listener to each HTML element through JavaScript, and then when the event triggers, the relevant function will be called.

Let's start with a simple example for the click event.

Event Listener with Click Event

html

index.html

copy
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>JavaScript Events with addEventListener</h1>
<p>This example uses the addEventListener() method to listen to click events on the button. Once a user clicks it,the text will be written on the demo element. </p>
<p id = 'demo'></p>
<button id = 'btn1'>Try it</button>
<script type = 'text/javascript'>
document.getElementById('btn1').addEventListener('click', myFunc);

function myFunc() {
document.getElementById('demo').innerHTML = 'I have done it';
}
</script>
</body>
</html>

Adding Multiple Event Listeners

You can add multiple event listeners to the same HTML element and call different functions for each triggered event. This is ideal in scenarios where the HTML element handles numerous events.

html

index.html

copy
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Multiple Event Listeners</h1>
<div id = 'divi' style = 'background-color:blue; width:150px;height:20px;padding:40px; color:white;'>Try it with your mouse <br>Text appears below </div>
<p id = 'demo'></p>
<script type = 'text/javascript'>
const divItem = document.getElementById('divi');
divItem.addEventListener('mouseover', myFunc);
divItem.addEventListener('mouseout', myFunc2);
divItem.addEventListener('click', myFunc3);

function myFunc() {
document.getElementById('demo').innerHTML += 'Mouse over! <br> ';
}

function myFunc2() {
document.getElementById('demo').innerHTML += 'Mouse out! <br> ';
}

function myFunc3() {
document.getElementById('demo').innerHTML += 'Clicked! <br> ';
}
</script>
</body>
</html>

Passing Parameters to Event Listeners

You can also pass parameters to an event listener. In the below example, you'll discover how you can pass the element that triggered the event and get its value. Likewise, you can pass any numerical values and so on.

html

index.html

copy
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Passing Parameters to addEventListener()</h1>
<p>This example demonstrates how to pass parameter values when using the addEventListener() method.</p>
<p>Click the button and it is passed as an argument and its value is displayed on the demo tag</p>
<button id = 'myBtn'>Try it</button>
<p id = 'demo'></p>
<script type = 'text/javascript'>
document.getElementById('myBtn').addEventListener('click', function() {
myFunction(this);
});

function myFunction(e) {
document.getElementById('demo').innerHTML = e.textContent;
}
</script>
</body>
</html>

Event Bubbling and Capturing

You can propagate events in the HTML DOM in two ways: bubbling and capturing.

Event propagation is the process of the occurrence of events from child elements to parent elements or vice versa.

Suppose there is a <div> element that houses a paragraph element, and if the event handler is placed on both elements, there will be a question of what happens when a user clicks on the <div> element, for instance.

  • Bubbling: The inner element handles the event first, followed by the outer element;

  • Capturing: The outer element handles the event first, followed by the inner element.

You can decide whether to use bubbling or capturing based on the parameters set on the useCapture parameter. By default, it is set to false, which is bubbling, and if set to True, it will use capturing.

js
addEventListener(event, function, useCapture);
html

index.html

css

index.css

copy
<!DOCTYPE html>
<html>
<head>
<link rel = 'stylesheet' href = 'index.css'/>
</head>
<body>
<div id = 'myDivi1'>
<h2>Bubbling:</h2>
<p id = 'p1'>Try Here</p>
</div>
<br>
<div id = 'myDivi2'>
<h2>Capturing:</h2>
<p id = 'p2'>Click me!</p>
</div>
<script>
document.getElementById('p1').addEventListener('click', function() {
alert('You clicked the red element!');
}, false);
document.getElementById('myDivi1').addEventListener('click', function() {
alert('You clicked the blue element!');
}, false);
document.getElementById('p2').addEventListener('click', function() {
alert('You clicked the red element!');
}, true);
document.getElementById('myDivi2').addEventListener('click', function() {
alert('You clicked the blue element!');
}, true);
</script>
</body>
</html>

1. Which is the correct way to add an event listener to a button element with an id 'demo' and call the function myFunc on the onclick event?

2. What's the difference between bubbling and capturing?

question mark

Which is the correct way to add an event listener to a button element with an id 'demo' and call the function myFunc on the onclick event?

Select the correct answer

question mark

What's the difference between bubbling and capturing?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

We use cookies to make your experience better!
some-alt