Event Listener Intro — JavaScript

Photo by Alireza Attari on Unsplash

Event listeners are my favorite part (so far) in JavaScript. They enable the user to interact with the web page without refreshing it when submitting a form, clicking a button, etc…

Below is a list of event listeners you can use to make your web page more interactive. You will find the link to MDN documentation for each of them if you would like further information.

MDN is a website known as one of the most reliable online documentation for Javascript as well as HTML and CSS.

1. Click listener

This is a mouse event reference that will listen for “clicks”, most commonly on a button. Please note this is not the best event listener to use when submitting a form. More details in part 2 of this blog.

HTML

JavaScript

Output: an alert pops up when the button “click here” is clicked

MDN documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

2. Form submit listener

There is a listener custom made for forms. It can listen to a click or “Enter” key pressed on the “submit” button of the form. Note that the event listener doesn’t listen to the submit button itself. It actually listens to the form element being submitted.

When the event is triggered, you can use the function preventDefault() against the event to stop the form from redirecting the user to a new page. To reset the form, add .reset() against the form element.

HTML

JavaScript

Output: Return the first name and the last name submitted in an alert box

MDN documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

3. Listens to select

This is an event that listens for text selection. You can also return what has been selected.

HTML:

JavaScript:

Output:

MDN documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event

4. Listens to Mouseover

This event will trigger if the mouse is moved over a particular element

HTML:

JavaScript:

Output:

MDN documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event

There are many other exciting event listeners you can use that I did not list in this blog. Please refer to the following link to see the full event reference list https://developer.mozilla.org/en-US/docs/Web/Events

Keep listening for events!

--

--

JavaScript Mid-Level Developer, I write blogs to learn and share what I learn.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aude Faucheux

JavaScript Mid-Level Developer, I write blogs to learn and share what I learn.