Event is an important part of a website. It gives the user a sense that the site is communicating.
In this article, we will learn about an event and how to add an event listener to a webpage.
An event is an action that happens when we manipulate a page.
For example, a “click” event happens when we click a button. It also happens when we type text into a textfield or move the cursor on something.
An event listener allows us to call functions when a specified event happens.
We use a method addEventListener() with the syntax:
target.addEventListener(event, function, useCapture)
Example
const button = document.querySelector(".btn");
button.addEventListener("click", function(event) {
alert("Hello World");;
})
// OR
button.addEventListener("click", event => alert("Hello World"));
We can also replace the function:
const button = document.querySelector(".btn");
button.addEventListener("click", buttonClick);
function buttonClick() {
alert("Hello World");
}
We have different event types:
An event is an object containing information about the action that just happened.
So when we listen to an event and run a function, we can pass in an event parameter. It’s optional.
We can console.log the event (e) and see the event object and its properties.
const button = document.querySelector(".btn");
button.addEventListener("click", buttonClick);
function buttonClick(e) {
console.log(e);
}