Skip to content

Events

Events occur as a result of the user's action on the website. Examples of such events are, for example, clicking a mouse button, scrolling the page, submitting a form or activating a certain field. Using JavaScript, we can react to such events and perform certain functions when they occur.

There are many events that we can handle. You can find the available event list here.

EventListener - adding listening

By selecting an element from the structure [DOM] (model_dom.md) we can add the so-called EventListener. Defining it will cause the function declared by us to be called when a specific action is performed by the user.

Let's create an EventListener for an element in the HTML below:

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>EventListenerDemo</title>
</head>
<body>
    <button id="id-button">Click</button>
</body>
</html>

The EventListener on the element is added using the addEventListener method, passing in the arguments the type of event we are listening for (as string)and a reference to function, which has to be called when the event occurs, e.g.

function displayText() {
    console.log("Tge button was clicked");
}

document.getElementById("id-button").addEventListener('click', displayText);

After clicking on the button element, thedisplayText function will be called, which will display the message defined by us in the console.

EventListener - removing listener

There is also an option to stop listening for an event. The method removeEventListener () is used for this, which we call, passing in arguments the type of event for which we no longer want to listen and a reference to the function that is to stop from being called.

function displayText() {
    console.log("Button was clicked");
    document.getElementById("id-button").removeEventListener('click', displayText);
}

document.getElementById("id-button").addEventListener('click', displayText);

In the example above, when clicking on the button, thedisplayText function will be invoked, which displays a message to the console and then stops listening for a click event. Another click on the button will not call the displayText() function anymore.