Events¶
Events occur as a result of the user's execution of actions on the website. Examples of such events can be: clicking the mouse button, scrolling the page, sending a form, or activating a certain field. Using JavaScript, we can react to such events and perform specific functions when they occur.
There are many events that we can handle. The available list of events can be found here.
EventListener - adding listener¶
Choosing an element from the DOM structure, we can add to it the so called EventListener. Defining it will call the function declared by us when the user performs a particular action.
Let's create an EventListener for the element in the HTML code below:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>EventListenerDemo</title>
</head>
<body>
<button id="id-button">Click me!</button>
</body>
</html>
The EventListener on the element is added using the addEventListener method, passing on in the arguments the type of event we are listening to (as string) and a reference to function to be called when the event occurs, e.g:
function displayText() {
console.log("The button has been clicked!");
}
document.getElementById("id-button").addEventListener('click', displayText);
When you click on the button
element, the displayText
function will be called, which will display a message (defined by us) in the console.
EventListener - removing listener¶
It is also possible to stop listening to an event. This is done by using the removeEventListener()
method, which we call up by passing on in the arguments the type of event we no longer want to listen to and a reference to the function that is to stop being called.
function displayText() {
console.log("The button has been clicked!");
document.getElementById("id-button").removeEventListener('click', displayText);
}
document.getElementById("id-button").addEventListener('click', displayText);
In the example above, when you click on the button
, the displayText
function will be called, which displays a message in the console and then stops listening to the click
event. Another click on the button
will no longer call up the displayText()
function.