Events in Javascript

Página 9

Events in Javascript

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:

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.

Next page of the Free Ebook:

10Working with forms in Javascript

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text