You are currently viewing Top 10 Important Event Listeners in Javascript

Top 10 Important Event Listeners in Javascript

List of Event Listeners Javascript

If you don’t know the event listener concept, you won’t understand the terminologies like two-way binding, events, dispatch events, etc used when you learn JS frameworks. So javascript event listener is the base for such topics. So, in this article, we’ll cover the most commonly used list of event listeners in JavaScript

What are event listeners?

You can easily handle users’ actions using a javascript event listener.  For example, if the user clicks a button, you can use an EventListener to tell what action to perform. We can handle the user’s interactions, like mouse clicks, keyboard presses, form submissions, or browser-related events, like page load or resize. You can’t design any interactive and dynamic web applications without using it.
We need to use addEventListener() an inbuilt function to create event listeners.  It plays a crucial role in detecting and responding to events triggered. Each action has an event keyword, For example, we use the click event to handle when the user clicks something and submit an event to handle the user submitting the form. And we can handle a particular user’s action by passing an event as an argument to addEventListener().

How event listener works?

Before you know the list of event listeners, you need to know how to detect and respond to events triggered by user interaction with event listeners. It consists of 3 main steps, there are:

1. Attaching the Event Listener

We can use the in-built function “addEventListener()”  to attach an event listener to an HTML element. We should specify the type of event (e.g., “click,” “mouseover,” “submit,” etc.) in the first argument, and in the second argument we have to call the function, this function will be run if the specified event is true. You can create the function separately and call it with the second argument, or create the anonymous function directly.
Example:
Here, we’ve passed the anonymous function directly in 2nd argument.
<button id="btnClick"> Click here </button>

const btnClick = document.getElementById("btnClick")

btnClick.addEventListener("click", ()=>{  
     btnClick.style.backgroundColor = "red";  
   });
In this example, we’ve passed the event “click” in the first argument, so if the user clicks the button, the background color of the button will change to red.

2. Detecting User Interactions

When the user interacts with the web page (e.g., clicks a button) the event listener detects a specific event.

3. Triggering the Event Listener

After the event is detected, the corresponding anonymous function or separate function you created in “addEventListener()” will be executed. Inside the event listener function, you can define custom tasks or actions as defined in the above example anonymous function. So, the response of the event is returned from the event listener function.

What are common JavaScript event listeners?

Your event lister function works depending on what you pass events in the first argument to the addEventListener() function. All events must be passed in single or double quotes. There are several events are available in Javascript, the commonly used events are:

1. click

This event is triggered when users right-click on an element like a button, link, etc.
HTML:
<button id="myButton">Click Here</button>
JS:
// Get reference to the Button element
 const button = document.getElementById('myButton');


//Create click Event lister for Btn
 button.addEventListener('click', () => {
    button.style.backgroundColor = "red";   //Change BG color
 });

2. submit

The “submit” event fires when the user submitted the form. It is one of the important list of event listeners in javascript.
HTML:
<!--Creating Form  -->
<form id="myForm">
  <input type="text" id="myInput">
  <button type="submit">Submit</button>
</form>


<!-- To display submitted value -->
<p id="myList">Your Submited Text: </p>
JS:
//Get reference by Id  to the form, text input, & p tag
const form = document.getElementById('myForm');
const input = document.getElementById('myInput');
const list = document.getElementById('myList');


//Add event listener form submit
form.addEventListener('submit', (event) => {
    event.preventDefault();     // Prevent form submission
    list.innerHTML = "Your Submited Text :" + input.value   // display value in <p>
    input.value = ' ' //clear data
    input.focus() //cursor focus
 });

3.mouseover

This event will fire when the user moves the mouse pointer over an element. Once the user hovers the mouse pointer over the element and exits, the event you have made will not remove because it will be set permanently.

HTML:

<!--Creating red div box  -->
<div id="myDiv1" style="width: 100px; height: 100px; background-color: red;"></div>
JS:
//Get the reference to the div element
const div1 = document.getElementById('myDiv1');


//Add event listener for Div
div1.addEventListener('mouseover', () => {
       div1.style.backgroundColor = 'blue';  // change bg-color red to blue
 });

4. change

This event will fire when the user makes a change on the screen. All changes can be made to user input elements. For example, This is triggered when the user adds or removes a value to an input type such as a checkbox, text, radio button, etc.
HTML:
<!--Creating Checkbox and para elements  -->
Checkbox<input type="checkbox" id="myCheckbox">
<p id="myPara"></p>
JS:
//Get reference by ID  to the input and para element
const checkBox = document.getElementById('myCheckbox');
const Para = document.getElementById('myPara');


//Add the change event for checkbox
checkBox.addEventListener('change', () => {
        Para.innerHTML = "The checkBox is :"+ checkBox.checked; // display the current change of checkbox
 });

5. mouseout

This event fires when the mouse pointer leaves an element and it won’t fire if the mouse is outside of the element without over. You can use this event when you want to perform some action or execute a function when the user’s mouse leaves
HTML:
<--Creating div box-->
<div id="myDiv1" style="width: 100px; height: 100px; background-color: red;"></div>
JS:
const div1 = document.getElementById('myDiv1');


//Add event listener for Div
div1.addEventListener('mouseout', () => {
       div1.style.backgroundColor = 'blue';  // change bg-color red to blue
 });

6. dblclick

The “dblclick” double-click event listeners in javascript are triggered when the element is clicked double times. You can use this event if you want to perform some action with a double click of a button, image, text, etc.
HTML:
<button id="myButton">Double-click me!</button>
JS:
// Get a reference to the button element
const myButton = document.getElementById('myButton');


// Add the event listener for the dblclick event
myButton.addEventListener('dblclick', function(event) {
    // Alert to be executed when the user double-clicks
    alert('Button double-clicked!');
    // You can perform any action or call a function here
});

7. keydown

This is the keyboard event because it triggers when the user pressed any key(button) on the keyword. You can use this code “event.key” to return the pressed key. But in the below example, we’ve logged the full event of the key.
HTML:
<input type="text" id="myButton">
JS:
myButton.addEventListener('keydown', function(event) {
    // Alert to be executed when the user double-clicks
    console.log(event);
});
 In this example, we have created the input text to get a keyword key. Then we’ve addEventListener() by passing keydown event and anonymous function. In the function, we’ve returned the event. Any keyword the user presses will be logged to the console as shown in the below image. You can easily find out which key the user pressed.
keydown event listener in js
The user typed “hi” in the input textbox. The user first pressed the “h” key, so its instance is logged to the console then pressed the “i” key its event is logged.

8. keyup

This event is triggered when the user releases the key(button) on the keyword.
HTML:
<input type="text" id="myInput" >
JS:
// Get a reference to the input element
const myInput = document.getElementById('myInput');


// Add the event listener for the keyup event
myInput.addEventListener('keyup', function(event) {
    // Code to be executed when a key is released
    console.log('Key released: ' + event.key);
    // You can perform any action or call a function here
});
keyup event listener in js
The keyup the event returns only the key released by the user. In the above image, only the key released by the user is logged without logging all the text in the input text box.

9. input

This event is triggered when the value of an input element changes. Not only input element, but you can also get the value of <textarea> tag by using the “input” event.
HTML:
<input type="text" id="textInput">
<div id="output"></div>
JS:
// Get references to the input element and the output div
const textInput = document.getElementById('textInput');
const outputDiv = document.getElementById('output');


// Add the event listener for the input event
textInput.addEventListener('input', function(event) {
    // Code to be executed when the input value changes
    outputDiv.textContent = 'You typed: ' + event.target.value;
});
input event listever in js
In this, we have changed the value of the input text box, so the user changed the value by actions such as typing, pasting, cutting, or deleting text in the input field shown in the div.

10. focus & blur

Focus event fires when the user gains focus on the element.  Usually, the user clicks or tabs into an input field to write something, so we can create an input text field with a focus event. Similarly, the blur event works when an element loses focus.
In this example, we have written a separate addEventListener() function for both focus and blur event . When the user focuses on the input field, the message “You’re focus now” is displayed. When the user is not focused on the input field, the message “You’re not focus now” is displayed.
HTML:
<input type="text" id="textInput">
<div id="output"></div>
JS:
// Get references to the input element and the output div
const textInput = document.getElementById('textInput');
const outputDiv = document.getElementById('output');

//Add the focus event listener

textInput.addEventListener('focus', () =>{
	outputDiv.innerHTML = "You're focus now"
});

//Add the blur event listener
textInput.addEventListener('blur', () =>{
	outputDiv.innerHTML = "You're not focus now"
});
When the user focused on the input text box:
focus event listener in javascript
When the user does not focus on the input text box:example of blur event in js
So, these are the most common  User Interface (UI) events used by developers. Similarly, events such as network, browser, drag and drop, and media are used, but only in rare cases. And you can also create your custom event by using the “CustomEvent” constructor. By creating your own event types and associated data to be dispatched and handled within your application.

Can we create an event listener without taking references?

Yes, If you have a unique IDname for your element, you don’t need to take a reference to the target element or object. If you use IDname there is no need to take reference because IDname is a unique name so we can directly invoke IDname and use addEventListner() function.
HTML:
<button id="button1">Button 1</button>
<button id="button2">Button 2</button
JS:
button1.addEventListener('click', () => {
      console.log(`Button 1 was clicked!`);
  });


button2.addEventListener('click', () => {
      console.log(`Button 2 was clicked!`);
  });
But if you have a class name, you must take a reference to your element. By using “document.querySelector()” or the “getElementsByClassName()” function, you can take class reference.
var Buttons = document.querySelector(".button1")

Buttons.addEventListener('click', () => {
      console.log(`Button 1 was clicked!`);
  });

How to see all event listeners?

There are several events in javascript and you can find all of them by following these below steps:
  1. Go to your browser and open Developer tools. (right click > inspect)
  2. Select the “Source” option on the top of the Dev tools.
  3. Click the “Event Listener Breakpoints” option in your right sidebar to see all events in Javascript.
event listeners javascript list

Conclusion

I hope you have understood the concept of a common list of event listeners in javascript. If you are strong in the 10 events I have listed in this article, you can easily understand other event listener concepts. By mastering event listeners in javascript , you’ll be better equipped to build powerful web applications. Happy coding!

Leave a Reply