[JavaScript] Understanding Onclick Event Listener and Various Ways to Code It.
Onclick, addEventListener(), DOM, querySelector(), getElementById()
Introduction
This article explores two ways of adding an event listener onclick().
Adding onclick="" property in your HTML tag.
Using addEventListener() method in JavaScript.
[JavaScript] Accessing the DOM Using JavaScript - Explained with Examples.
Onclick Property in HTML Tag
Onclick property is written in your HTML tag, and receives the function after the assignment operator(=).
That function is executed when the user clicks a button.
Before going through this article, if you don't know how to access the DOM(document object model), check out this article.
<!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>Document</title>
</head>
<body>
<button onclick="doSave();" id="btn">Save</button>
</body>
<script>
function doSave() {
// code in here will be executed when the user clicks a button
}
</script>
</html>
Using addEventListener Method in JavaScript
You can use an addEventListener method to do the same task as above.
I prefer using this, and many developers also prefer to do this because your code is more manageable and readable.
Imagine you have a thousand lines of HTML code. It would be quite hard to manage them. So, we can create a function in JavaScript to make it more manageable.
AddEventListener receives two parameters:
Event type
Function that will be executed when the event happens.
<!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>Document</title>
</head>
<body>
<button id="btn">Save</button>
</body>
<script>
function addClickEvent() {
document.querySelector("#btn")
.addEventListener("click", function() {
// code in here will be executed when the user clicks a button
}
}
</script>
</html>
What the function addClickEvent() is doing:
Access the DOM by using the id="btn".
Specifies that the event listener "click" is added.
When a user clicks a button, anything inside the function (second parameter of addEventListener) will be executed.