Events in Javascript
Page 9 | Listen in audio
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: