If you are someone who is interested in learning JavaScript, one of the most important things you should learn is how to make your web pages interactive. Webpages can be made interactive with the help of JavaScript events. JavaScript events include what is happening in the browser, such as clicking a button, moving the mouse, or pressing a key. JavaScript provides you with mechanisms with which you can react to these operations and make your web pages attractive.
In this blog, you will learn about JavaScript events, how they work, how to handle them using event handling in JavaScript, how you can attach JavaScript event listeners, and how you can use event delegation in JavaScript. So let’s get started!
Table of Contents:
What is an Event?
Events are basically the actions that occur on a webpage when you interact with it. In simple terms, a JavaScript event is an action that occurs when a user performs an act such as clicking a button, writing an input text field, or resizing the browser window. Sometimes, events can also be triggered by the browser itself, like when the page finishes loading or when the page is closed. These events help you to run specific code in response to what is happening on the page.
The most common events that you can experience on the web page are when the page finishes loading, submitting a form, entering text, clicking a link, or while playing or pausing a video.
Master Web Development
Learn to Build Stunning Websites and Apps from Scratch
What are JavaScript events?
JavaScript events are the actions that happen on the web page when you click on it, move the mouse, or click a button. When these actions happen, JavaScript can respond to them using event handling. This can be done by adding a JavaScript event listener, which waits for the actions to take place and then runs your code. If you have many items, you can add event delegation in JavaScript instead of an event listener. This helps to handle those items with just one listener on the parent element. This helps to make your code cleaner and faster.
A sample code for JavaScript events is given below for your reference:
Code:
Explanation:
The JavaScript code above assumes that you have the elements in your HTML code, whose IDs are showMessageBtn (which is an identifier of the button) and outputText (an identifier of the paragraph in which the message should be displayed).
Given below is the entire HTML code that contains the JavaScript code for handling a button click event. This provides you with the desired output.
Code:
Output:
Explanation:
Here, when you click on the “Click Me” button, a JavaScript click event starts working. This event is caught using something called an event listener. It listens for the click and then runs your code. In this case, the text is changed by the code by updating it with a message using the textContent property. This is how your webpage responds to the actions and becomes interactive.
Types of JavaScript Events
JavaScript consists of many types of events that help you respond to different actions on a webpage. Given below are some of the common examples of the types of events in JavaScript:
- Mouse Events: Mouse events take place when the mouse is used. Some examples of mouse events are: click, dblclick, mousemove, mouseover, mouseout.
- Keyboard events: Keyboard events take place when the keys on the keyboard are pressed. Some examples of keyboard events are: keydown, keypress, keyup.
- Form events: Form events occur when users interact with the form fields. Some examples of form events are: submit, change, focus, and blur.
- Window events: Window events are the type of events that are related to the browser window. Some examples of window events are: load, resize, and scroll.
Common JavaScript Events
Some of the common JavaScript events are mentioned below in tabular format:
Event Name |
When It Happens |
click |
When clicking on a button, a link, or any other component |
dblclick |
When you double-click on an element |
mouseover |
When your mouse pointer moves over an element |
mouseout |
When your mouse pointer moves away from an element |
mousemove |
When you move the mouse around on the page or over an element |
mousedown |
When you press down a mouse button |
mouseup |
When you release a mouse button after clicking |
keydown |
When you press any key on the keyboard |
keyup |
When you release a key after pressing it |
keypress |
When you press and hold a key (used less now; better to use keydown) |
submit |
When a form is submitted |
change |
Upon modifying the value in a form field, such as a dropdown or checkbox |
focus |
When a form field is clicked into or becomes active |
blur |
When a form field loses focus or becomes inactive |
input |
When a user inputs something in a text field |
load |
When a page, image, or resource has fully loaded |
resize |
When the browser window is resized |
scroll |
When you scroll up or down the page |
unload |
When you are about to leave the page (not commonly used now) |
contextmenu |
When you right-click to open the context menu |
dragstart |
When you start dragging an element |
dragend |
When you finish dragging an element |
touchstart |
When you touch the screen on mobile devices |
touchend |
When you lift your finger off the screen on a mobile device |
Some of the common JavaScript Events are explained below in brief:
1. Click Event
The JavaScript click event occurs when you click on an object, such as a button or a link. It allows you to execute your code with a single click and do something with it: display a message or update the page information. It is one of the most commonly used events to make webpages interactive.
Given below is an HTML code that contains the JavaScript code for the click event.
Code:
Output:
Explanation:
The above HTML code is used to create a simple webpage with a button. When you click on the “Click Me” button, a JavaScript function called showMessage() runs. This function is able to find the empty paragraph below the button and updates the text “You have clicked the button!” It uses the event onclick to respond when the button is clicked to show how a basic JavaScript click event works.
2. Mouseover Event
The mouseover event occurs when a mouse is moved over any element, such as a heading or a button. It helps you to run JavaScript code when you move the mouse into that area. This can be applicable for things such as displaying tooltips or changing styles.
Given below is an HTML code that contains the JavaScript code for the mouseover event.
Code:
Output:
Explanation:
The above code displays a message when you move your mouse over the text. The event onmouseover is used to run the hoverText() function. This updates the paragraph below to say “Mouse is over the text!” with the help of JavaScript.
Get 100% Hike!
Master Most in Demand Skills Now!
3. Keydown Event
The keydown event occurs whenever a key is pressed on the keyboard. It helps you to run the JavaScript code as a key is pressed down. It can be used in the case of live search management or shortcuts.
Given below is an HTML code that contains the JavaScript code for the keydown event.
Code:
Output:
Explanation:
The above code is used to show the working of the keydown event. When any key is pressed inside the input box, the keyPressed() function starts to run. It updates the paragraph below and shows the message “Key pressed!”. This happens immediately when the key is pressed down.
4. Submit Event
The submit event takes place whenever you submit a form. It is usually done by clicking a submit button. You can use it to run JavaScript code before you send the form data, like checking if the fields are filled. It can be useful for the validation of forms without refreshing the page.
Given below is an HTML code that contains the JavaScript code for the submit event.
Code:
Output:
Explanation:
The above code is used to show how the submit event works in JavaScript. After you fill in the input and click on the submit button, the function handleSubmit() runs. It uses an event. preventDefault () to stop the page from reloading. After that, it displays the page “Form submitted successfully”. This helps you to handle forms and actions without refreshing the page.
5. Change Event
The change event in JavaScript is executed when the value of a form field is changed, and the user presses Enter. It is usually applied in dropdowns or text fields, which allows identifying when the user chooses or writes something.
Given below is an HTML code that contains the JavaScript code for the change event:
Code:
Output:
Explanation:
The above is used to show the working of the change event in JavaScript. Whenever you choose either “About” or Contact”, the function selectChanged() is used to run and update the paragraph below, along with the message “You changed the selection”. This occurs as soon as you pick up a different option.
6. Load Event
The load event takes place when the whole web page or a part of the webpage finishes loading. It can be useful when you want to run a code after everything is ready on the page, like showing a welcome message or hiding a loading screen.
Given below is an HTML code that contains the JavaScript code for the load event:
Code:
Output:
Explanation:
The above code is used to show how the load event works. When the loading is finished on the entire page, the function window.onload runs. After that, it updates the paragraph with the message “Page has loaded!” to confirm that everything is loaded on the page.
The scroll event occurs when you try to move up or down a webpage. It helps you to run JavaScript code while scrolling, like showing a sticky header or loading more content as you keep scrolling.
Given below is an HTML code that contains the JavaScript code for the scroll event:
Code:
Output:
Explanation:
This code shows how the scroll event works in JavaScript. When you scroll up or down the page, the event listener detects it and changes the text of the fixed paragraph to “You are scrolling!” This gives you instant feedback whenever the page is being scrolled.
8. Focus Event
The focus event takes place when the input field or form element becomes active when you click on it. This can be used to show hints, change styles, or perform actions as soon as you start to interact with a field.
Given below is an HTML code that contains the JavaScript code for the focus event:
Code:
Output:
Explanation:
The above code is used to show how the focus event works. When you click on the input field, the fieldFocused() function starts running and updates the paragraph below with the message “Input field is focused!”. This shows that the field is active and ready to input.
9. Blur Event
The blur event takes place when you click away from an input field. It helps you to run the code when the field is no longer active, like checking if the input is filled or hiding a message.
Given below is an HTML code that contains the JavaScript code for the blur event:
Code:
Output:
Explanation:
The above code is used to show how the blur event works. When you click on the input field and click away, the function fieldBlurred() starts running. Then it updates the following paragraph with the message “Input field lost focus!” This shows the field is no longer active.
JavaScript Event Handlers
You can use JavaScript event handlers whenever something happens on a webpage, like clicking a button, typing a field, or moving the mouse. This helps to make your page interactive. This process is called event handling in JavaScript. In this process, the code runs when a specific event occurs.
Types of JavaScript Event Handlers
There are basically three types of event handlers in JavaScript:
1. Inline Event Handlers
2. DOM Property Handlers
3. Using addEventListener()
Each of the three types of Event Handlers is explained below:
1. Inline Event Handlers
This method helps you to handle events directly in the HTML tag by using attributes like onclick, onmouseover, etc.
Example: Inline onclick Handler
Output:
Explanation:
The above is used to show the working process of an inline event handler in JavaScript. When you click on the “Click Me” button, the showMessage() function is called by the onclick attribute. This function then updates the paragraph that is under the message “Button clicked using inline handler!” Therefore, it is a simple way for you to handle events directly in HTML.
2. DOM Property Handlers
DOM property handlers are a simple way to handle events in JavaScript. This can be done by immediately assigning a value as a function to the event property of the element, such as element.onclick or element.onchange. It is easy to use for small tasks, but you can only assign one handler for one event. Adding another handler will replace the previous one.
Example: Click Event using DOM Property Handler
Output:
Explanation:
The above code is used to show how you can use a DOM property handler to handle a click event. Clicking on the “Click Me” button causes the onclick property to execute a function, which changes the text in the paragraph to the text of the Button clicked using the DOM property!
3. Using addEventListener()
This is the modern and most preferred way to handle events in JavaScript. It separates HTML from JavaScript and gives more control.
Example: Click Event using addEventListener()
Output:
Explanation:
The above code uses the addEventListener() method to handle a click event. When you click on the “Click Me” button, a function is run by the event listener, which changes the paragraph with the message “Button clicked using addEventListener!”. This helps you to attach multiple event handlers and helps to keep your JavaScript code separate from HTML.
Event Propagation in JavaScript
Event propagation in JavaScript is the way events move through the HTML elements on a web page. When an event takes place, like clicking a button inside a <div> tag, JavaScript decides how to handle it by moving through three phases:
1. Capturing Phase: In the capturing phase, the event starts from the top and moves down to the target element.
2. Target Phase: During the Target Phase, the event is reached by the particular element that was clicked.
3. Bubbling phase: In the bubbling phase, the event moves up from the target to the top.
Example: Event Propagation (Bubbling Phase)
Output:
Explanation:
The above code is used to show how event bubbling works. When you click on the button, it first shows “Button clicked!” Since the button is inside the <div> tag, the event moves up and also triggers the <div> tag’s alert that shows “Div Clicked!”. It shows that one click can affect both the button and its parent.
Event Delegation in JavaScript
Event Delegation in JavaScript is an easy way to handle events for many elements by using just one event listener on their parent. Instead of adding a separate click event to each item, you add one click event to the parent. When any child is clicked, the event moves up to the parent, and then you can check which child was clicked. This makes your code simple and easy to understand.
Example: Event Delegation on List Items
Output:
Explanation:
The above code is used to show the working of event delegation in JavaScript. Instead of having a click event on each list item, one event listener is added to the parent <ul>. When you click on any <li>, the event moves up to the parent, and the script checks if the element you have clicked is a list item. If it is so, it shows a message like “Item 1 was clicked!” in the paragraph below.
Applications of JavaScript Events
Some of the applications of JavaScript events are given below:
1. User Interaction Handling: The JavaScript events are applied to respond to clicks, scrolls, hovers, and clicking keys on a page.
2. Form validation: JavaScript events are also used to check and validate fields before you submit the form.
3. Dynamic Content updates: It is also used to show/hide elements or change styles instantly on the actions of the user.
4. Interactive games and animation: It is also used to control movements and effects using the movements of the mouse and keyboard.
5. Real-time input feedback: It is also used to display live suggestions or messages as you type.
Conclusion
Having a good understanding of JavaScript events is important for you if you want to build responsive web applications. Whether you use event handling in JavaScript to make a button clickable, add a JavaScript event listener to allow a real-time interaction, or use event delegation in JavaScript to be efficient, you are enabling your webpages to react to user actions smoothly. Hence, it is important for you to master event handling in JavaScript as it is a very important step towards building smooth, dynamic, and interactive websites. To learn more about JavaScript, explore the JavaScript Interview Questions and subscribe to our Web Development Course.
JavaScript Events – FAQs
Q1. What is a JavaScript event?
A JavaScript event is a web page activity, such as clicking on the page or pressing keys.
Q2. What is the difference between onclick and addEventListener()?
onclick adds one event, while addEventListener() lets you add multiple events and more control.
Q3. Can I remove an event after adding it?
Yes, because with addEventListener(), you can remove it by using removeEventListener().
Q4. What is event bubbling?
Event bubbling refers to the event traveling up the parent elements to an element that is clicked.
Q5. Why should I use event delegation?
It helps you to save time by handling events for multiple items using only one listener on their parent.