Events in Javascript

Capítulo 9

Estimated reading time: 2 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

Javascript is a programming language widely used in the development of websites and one of its main characteristics is the ability to interact with the user through events. Events are actions that occur in the user's browser, such as clicking a button, typing in a form field, or scrolling down the page.

To handle events in Javascript, it is necessary to use the addEventListener() method, which allows associating a function with a specific event. For example, to execute a function when the user clicks on a button, we can use the following code:

const button = document.querySelector('#my-button');

button.addEventListener('click', function() {
  alert('The button was clicked!');
});

In this example, we use the querySelector() method to select the button with the id "my-button" and add an event listener for the "click" event. When the user clicks on the button, the anonymous function passed as the second parameter will be executed and will display an alert on the screen.

In addition to the "click" event, there are several other events that can be used in Javascript, such as "submit" (when a form is submitted), "keydown" (when a key is pressed) and "scroll" (when the page is scrolled).

It is also possible to remove an event listener using the removeEventListener() method. For example, if we wanted to remove the event listener for the button from the previous example, we could use the following code:

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app

button.removeEventListener('click', myFunction);

It is important to remember that events in Javascript can be used to create more dynamic and attractive interactions on websites, but they must also be used carefully so as not to overload the user's browser and impair the user experience.

Now answer the exercise about the content:

_Which method is used in Javascript to associate a function to a specific event?

You are right! Congratulations, now go to the next page

You missed! Try again.

The method used in Javascript to associate a function to a specific event is addEventListener(). It allows developers to specify event handlers for various events like 'click', 'submit', 'keydown', etc., enabling interactive and dynamic websites.

Next chapter

Working with forms in Javascript

Arrow Right Icon
Free Ebook cover How to use Javascript in website development
24%

How to use Javascript in website development

5

(2)

37 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.