Javascript is a great tool to make it so that the webpage can come alive. One way to do this in Javascript is using event listeners. Event listeners allow the user to interact with the webpage in real time.
The event listener listens for an event to happen and then runs a callback function to do an actions. The event listener is added on an element in which an event will happen.
The event listener is set up in a way that even if the function is anonymous it will still be run. The event listener knows to run the function in the 2nd argument when the event takes place.
Typically the parameter of the function in an event listener is named event or e. Then an array of attributes is produced when the event happens and those items can be gathered by creating a variable that takes the target of the event and stores it.
Some frequently used event listeners are clicks, submits, DOMcontent loaded, and buttons. So more unique and less frequently used event listeners are ones related to the mouse's location.
An example of an event listener in Javascript can be seen below:
(In the HTML there would be a button element that had the ID of button.)
const button= document.getElementById('button');
button.addEventListener('click', function() {
alert('This button was clicked!');
});
What this code does is when the button is click a message appears on the top of the page that says. This page says: This button was clicked! To get out of that alert the user presses the ok button.
Top comments (0)