DEV Community

Spencer Adler
Spencer Adler

Posted on

Event Listeners in Javascript

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.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

๐Ÿ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someoneโ€™s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay