Events In JavaScript
In this section, you will learn about javascript events. We look at different types of events, how to handle them and how to use them.
JavaScript Events
Events are the actions that occur in the browser. They are the actions that the user performs on the browser.
Events are also the actions performed on HTML elements by the user. For example, when the user clicks on a link, the browser sends an event to the server. The server can then take some action based on the event. For example, the server can send a message to the user.
Some of the simple examples of events are:
- Button click
- Mouse click
- Keyboard input
- Form submission
- Page load
- Window resize
Let us see an example of the click event. Click the button below to see the event in action.
The above buttons are used to demonstrate the different types of events.
Handling events in javascript
Each event in javascript has something that is constantly looking for that event to occur which is called event listener.
The event listener triggers a function execution whenever the event occurs. These functions can be a regular function, arrow function, or anonymous function.
Generally, event listener and event handler are used interchangeably.
Here is how an event is handled in javascript step by step:
- The event is triggered by the user.
- The event is caught by the browser.
- The event is passed to the event listener.
- The event listener is called which calls the function that is passed to it.
Add Event Listener
There are 2 ways to add an event listener to an element in javascript:
- Using the addEventListener() method.
- Using the on attribute. for example
onclick
,onmouseover
, etc.
1. Using the addEventListener() method
The addEventListener() method is used to add an event listener to an element. The addEventListener() method takes 2 arguments:
- event - The event that is being listened for.
- listener - The function that is called when the event occurs.
The event argument is the name of the event that is being listened to. The listener argument is the function that is called when the event occurs.
The addEventListener() method returns the listener
argument.
Example
<button id="btn">Alert!</button>
<script>
// selecting the element
const btn = document.getElementById('btn');
// adding event listener
btn.addEventListener('click', alertMessage);
// event handler function
function alertMessage() {
alert('Hello World!');
}
</script>
Try It
2. Using the on attribute
Using the on attribute method you can directly add an event listener to the HTML element. Examples of attributes are onclick
, onmouseover
, etc.
The on attribute takes a string as an argument. The string is the name of the event that is being listened to.
Example
<button onclick="alertMessage()">Alert!</button>
<script>
// event handler function
function alertMessage() {
alert('Hello World!');
}
</script>
Try It
Remove Event Listener
To remove an event listener from an element, you can use the removeEventListener() method.
The removeEventListener() method takes 2 arguments, event and listener.
Note: The removeEventListener() method only remove those event listeners that were added using the addEventListener() method.
Example
<button id="btn1">Alert!</button>
<button onclick="removeEvent()">Remove Event Listener</button>
<script>
// selecting the element
const btn = document.getElementById("btn1");
// adding event listener
btn.addEventListener("click", alertMessage);
// function to alert message
function alertMessage() {
alert("Hello World!");
}
// function to remove event listener
function removeEvent() {
btn.removeEventListener("click", alertMessage);
}
</script>
Try It
Types of Events in Javascript
There are many different types of events in javascript. The following are some of the most common types of events:
- Window Events
- Mouse Events
- Keyboard Events
- Form Events
- Storage Events
- Media Events
- Drag Events
- Clipboard Events
1. Window events in javascript
The window object is the top-level object in the browser. It is the parent of all other objects in the browser.
The window object has a number of events that can be listened to. The following are the most common window events shown in the table below:
Event | Action | Description |
---|---|---|
onload | webpage loaded | The onload event is triggered when the page is loaded. |
onresize | resizing browser tab | event is triggered when the browser window is resized. |
onresize | scrolling browser tab | event is triggered when the browser window is scrolled. |
onbeforeunload | before closing browser tab | event is triggered when the browser window is about to be closed. |
onoffline | when the browser is offline | event is triggered when the browser is offline. |
ononline | when the browser is online | event is triggered when the browser is online. |
onload event
If you want to execute a function when the page is loaded, you can use the onload event.
This event is triggered when the page is loaded.
Example
<body onload="alert('Page loaded!')">
<p>As soon a page loaded it alerts "Page loaded!" message.</p>
</body>
Try It
onresize event
The onresize event is triggered when you resize the browser window.
Example
<body onresize="resizeW()">
<script>
function resizeW() {
console.log('The window has been resized');
}
</script>
</body>
Try It
onbeforeunload event
The onbeforeunload event is triggered when the user attempts to close the browser tab.
Example
<body onbeforeunload="return confirm('Are you sure you want to close the tab?')">
<p>If you close the tab, it will ask you to confirm.</p>
</body>
Try It
onoffline event
The onoffline event is triggered when the browser is offline.
Example
<body onoffline="offLine()">
<p id="demo"></p>
<script>
function offLine() {
const demo = document.getElementById("demo");
demo.innerHTML = "You are offline";
demo.style.color = "red";
}
</script>
</body>
Try It
ononline event
The ononline event is triggered when the browser is online.
Example
<body ononline="onLine()">
<p id="demo"></p>
<script>
function onLine() {
const demo = document.getElementById("demo");
demo.innerHTML = "You are online";
demo.style.color = "green";
}
</script>
</body>
Try It
2. Mouse events in javascript
Mouse events are those events that are triggered on some activity by the mouse, like clicking, hovering, dragging, etc.
The following is the list of mouse events in JavaScript:
Event | Action | Description |
---|---|---|
click | Mouse click | when the mouse is clicked over an element |
dblclick | Mouse double click | Mouse double clickwhen the mouse is double-clicked over an element |
mouseover | Mouse over | Triggered when the user moves the mouse over an element |
mouseout | Mouse out | Triggered when the user moves the mouse out of an element |
mousedown | Mouse button down | Triggered when the user presses the mouse button. |
mouseup | Mouse button up | Triggered when the user releases the mouse button. |
mousemove | Mouse move | Triggered when the user moves the mouse over an element |
mouseenter | Mouse enter | Triggered when the user moves the mouse over an element |
mouseleave | Mouse leave | Triggered when the user moves the mouse out of an element |
click event
The click event is triggered when the user clicks the mouse button.
Example
<p id="elm" onclick="changeColor()">Click this element</p>
<script>
function changeColor() {
document.getElementById("elm").style.color = "red";
}
</script>
Try It
Output
Click this element
dblclick event
The dblclick event is triggered when the user double click the mouse button.
Note: When you double click the mouse button then the click event is triggered first 2 times and then the dblclick event is triggered.
Example
<p id="elm" ondblclick="changeColor()">Double click this element</p>
<script>
function changeColor() {
document.getElementById("elm").style.color = "red";
}
</script>
Try It
Output
Double click this element
mouseover event
When you take the mouse cursor over an element then the mouseover event is triggered.
You can use this event to perform some action when the mouse cursor is over an element like changing the color of the element.
Example
<button onmouseover="changeColor()" id="btn">Change Color</button>
<script>
function changeColor() {
document.getElementById("btn").style.backgroundColor = "red";
}
</script>
Try It
Output
mouseout event
When you take the mouse cursor out of an element then the mouseout event is triggered.
You can also use it to reverse the action of the mouseover event.
Example
<button onmouseover="changeColor()" onmouseout="reverseColor()" id="btn">Change Color</button>
<script>
function changeColor() {
document.getElementById("btn").style.backgroundColor = "red";
}
function reverseColor() {
document.getElementById("btn").style.backgroundColor = "white";
}
</script>
Try It
Output
mousedown event
The mousedown event is triggered when the user presses the mouse button.
You can use this event to open some pop-up or to perform some action when the mouse button is pressed over an element.
Example
<button onmousedown="openPopup()" id="btn">Open Popup</button>
<div id="popup">
<p>This is a popup</p>
</div>
<script>
function openPopup() {
document.getElementById("popup").style.display = "block";
}
</script>
Try It
mouseup event
The mouseup event is triggered when the user releases the mouse button.
You can use this event to close some pop-up or to perform some action when the mouse button is released over an element.
Example
<button onmousedown="openPopup()" onmouseup="closePopup()" id="btn">Open/close Popup</button>
<div id="popup">
<p>This is a popup</p>
</div>
<script>
function openPopup() {
document.getElementById("popup").style.display = "block";
}
// Close the popup
function closePopup() {
document.getElementById("popup").style.display = "none";
}
</script>
Try It
mousemove event
The mousemove event is triggered when the user moves the mouse over an element.
In the example below, we have used the mousemove event to track the position of the mouse cursor.
Example
<button onmousemove="trackMouse()" id="btn">Track Mouse</button>
<script>
function trackMouse() {
var x = event.clientX;
var y = event.clientY;
document.getElementById("btn").innerHTML = "Mouse position: " + x + ", " + y;
}
</script>
Try It
Output
mouseenter event
The mouseenter event is triggered when the mouse enters an element.
To check this event in action we will change the background color of an element when the mouse enters it.
Example
<div onmouseenter="changeColor()" id="div">
<p>This is a div</p>
</div>
<script>
function changeColor() {
document.getElementById("div").style.backgroundColor = "blue";
}
</script>
Try It
Output
This is a div
mouseleave event
The mouseleave event is triggered when the mouse leaves an element.
You can also use this event to reverse the changes made by the mouseenter event or can do some other action.
Example
<div onmouseenter="enterColor()" onmouseleave="leaveColor()" id="div">
<p>This is a div</p>
</div>
<script>
function enterColor() {
document.getElementById("div").style.backgroundColor = "blue";
}
function leaveColor() {
document.getElementById("div").style.backgroundColor = "red";
}
</script>
Try It
Output
This is a div
3. Keyboard events in javascript
Keyboard events are those events that are triggered when you press a key on your keyboard.
There are many different types of keyboard events in javascript. Some of them are:
Event | Action | Description |
---|---|---|
onkeydown | Button Down | event is fired when any keyboard button is down |
onkeyup | Button released | event is fired when any keyboard button is released |
onkeypress | Button pressed | event is fired when any keyboard button is pressed |
keydown event
The keydown event is triggered when a key is pressed down.
As soon as you press a key, the browser will fire the keydown event.
Example
<p id="output"></p>
<textarea onkeydown="keyDown()"></textarea>
<script>
var count = 0;
function keyDown() {
var output = document.getElementById('output');
count++;
output.innerHTML = "You pressed: " + event.key + ", numberof times: " + count;
}
</script>
Try It
Output:
keyup event
The keyup event is triggered when a key is released.
As soon as you release a key, the browser will fire the keyup event.
Example
<p id="output"></p>
<textarea onkeyup="keyUp()"></textarea>
<script>
var count = 0;
function keyUp() {
var output = document.getElementById('output');
count++;
output.innerHTML = "You released: " + event.key + ", numberof times: " + count;
}
</script>
Try It
Output:
keypress event
The keypress event is triggered when a key is pressed and released.
As soon as you press and release a key, the browser will fire the keypress event.
When you compare the keypress event to the keydown event then keydown event is triggered before keypress event.
Example
<p id="output"></p>
<textarea onkeypress="keyPress()"></textarea>
<script>
var count = 0;
function keyPress() {
var output = document.getElementById('output');
count++;
output.innerHTML = "You pressed: " + event.key + ", numberof times: " + count;
}
</script>
Try It
Output:
4. Form events in javascript
Forms in HTML have many different types of events that can be triggered at different action points.
The form events in javascript are:
Event | Action | Description |
---|---|---|
submit | onsubmit | event is fired when the form is submitted |
focus | onfocus | event is fired when the cursor is focused on form |
blur | Focus Removed | event is fired when the focus is removed from input section |
change | onchange | event is fired when the value of the input is changed |
reset | onreset | event is fired when the form is reset |
select | onselect | event is fired when a selection is made |
submit event
The submit event is triggered when you submit the form.
Note: submit event by default refreshes the page when the form is submitted.
Example
<form onsubmit="submitForm(event)">
<input type="text" name="name" placeholder="name">
<input type="text" name="email" placeholder="email">
<input type="submit" value="submit">
</form>
<script>
function submitForm(event) {
event.preventDefault();
alert('form submitted');
}
</script>
Try It
Output:
focus event
The focus event is triggered when the input gains focus.
Example
<input type="text" onfocus="focusInput(this)">
<script>
function focusInput(event) {
event.style.backgroundColor = 'orange';
}
</script>
Try It
Output:
blur event
The blur event is triggered when the input loses focus.
Example
<input type="text" onblur="blurInput()">
<script>
function blurInput() {
alert('focus removed');
}
</script>
Try It
Output:
change event
The change event is triggered when the value of an input changes.
Example
<input type="text" onchange="changeInput()">
<p id="output"></p>
<script>
function changeInput() {
document.getElementById('output').innerHTML = this.value;
}
</script>
Try It
Output:
Change the input field and click outside the input field to see the output.
reset event
The reset event is triggered when the form is reset.
There lies an input type called reset, which is not a submit button. It is used to reset the form.
Example
<form onreset="resetForm()">
<input type="text" name="name" placeholder="name">
<input type="text" name="email" placeholder="email">
<input type="reset" value="reset">
</form>
<script>
function resetForm() {
alert('form reset');
}
</script>
Try It
Output:
select event
The select event is triggered when a new input is selected.
In the example below, we are going to use the select element to select the input field.
Example
<select name="cars" onchange="selectInput()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script>
function selectInput() {
alert('you selected: '+this.value);
}
</script>
Try It
Output:
5. Storage Event in JavaScript
The Storage Event is triggered when the storage area is changed.
Note: The storage event triggered only when the storage area of another window is changed not the current window.
The following example shows how to use the Storage Event in JavaScript.
Example
<button onclick="addItemLocalStorage()">Add item to local storage</button>
<script>
// add new item to local storage
function addItemLocalStorage() {
var newWindow = window.open("");
newWindow.localStorage.setItem("name", "John");
newWindow.close();
}
window.addEventListener("storage", storageEvent);
function storageEvent() {
alert("Storage changed");
}
</script>
Try It
6. Media Events in JavaScript
Media events are events that are triggered by media elements. These events are triggered when different actions are taken or occur on the media element.
The list of media events is shown in the table below.
Event | Description |
---|---|
abort | Triggered when the loading of an audio/video is aborted. |
canplay | Triggered when the browser can start playing the audio/video. |
canplaythrough | Triggered when the browser can play through the audio/video without stopping for buffering. |
durationchange | Triggered when the duration of the audio/video is changed. |
emptied | Triggered when the current playlist is empty. |
ended | Triggered when the current playlist is ended. |
error | Triggered when an error occurs. |
loadeddata | Triggered when the browser has loaded the current frame of the audio/video. |
loadedmetadata | Triggered when the browser has loaded meta data for the audio/video. |
loadstart | Triggered when the browser starts looking for the audio/video. |
pause | Triggered when the audio/video is paused. |
play | Triggered when the audio/video is played. |
playing | Triggered when the audio/video is playing. |
progress | Triggered when the browser is downloading the audio/video. |
ratechange | Triggered when the playing speed of the audio/video is changed. |
sought | Triggered when the user is finished moving/skipping to a new position in the audio/video. |
seeking | Triggered when the user starts moving/skipping to a new position in the audio/video. |
stalled | Triggered when the browser is trying to get media data, but data is not available. |
suspend | Triggered when the browser is intentionally not getting media data. |
timeupdate | Triggered when the current playback position has changed. |
volumechange | Triggered when the volume has been changed. |
waiting | Triggered when the video stops because it needs to buffer the next frame. |
7. Drag Events in JavaScript
Drag events are events that are triggered by drag and drop actions.
When you drag a draggable element, the browser fires the dragstart event. This event is followed by a number of events, depending on the type of drag action.
The list of drag events is shown in the table below.
Event | Description |
---|---|
ondrag | Triggered when an element is being dragged |
ondragend | event occurs when an element stops being dragged |
ondragenter | event occurs when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds). |
ondragleave | event occurs when an element or text selection leaves a valid drop target. |
ondragover | event occurs when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds). |
ondragstart | event occurs when an element is being dragged |
ondrop | event occurs when an element or text selection is being dropped on a valid drop target. |
Here is an example that shows different drag events in action.
Example
<p draggable="true" ondrag="onDrag()" ondragstart="dragStart()" ondragend="dragEnd()">Drag me</p>
<textarea ondragenter="dragEnter()" ondragleave="dragLeave()" ondragover="dragOver(event)"></textarea>
<p id="output"></p>
<script>
const output = document.getElementById("output");
function onDrag() {
output.innerHTML += "Dragging...<br>";
}
function dragStart() {
output.innerHTML = "Dragging started...<br>";
}
function dragEnd() {
output.innerHTML += "Dragging ended...<br>";
}
function dragEnter() {
output.innerHTML += "Dragging entered...<br>";
}
function dragLeave() {
output.innerHTML += "Dragging left...<br>";
}
</script>
Try It
8. Clipboard Events in JavaScript
Clipboard events are events that are triggered by the copy, cut, and paste actions.
The list of clipboard events is shown in the table below.
Event | Description |
---|---|
oncopy | Triggered when the user copies text to the clipboard. |
oncut | Triggered when the user cuts text to the clipboard. |
onpaste | Triggered when the user pastes text from the clipboard. |
copy event
When you copy text to the clipboard, the browser fires the oncopy event.
Example
<p oncopy="copy()">Copy me!</p>
<script>
function copy() {
alert("Copied!");
}
</script>
Try It
cut event
When you cut text to the clipboard, the browser fires the oncut event.
Example
<input type="text" oncut="cut()" value="Cut Me!">
<script>
function cut() {
alert("Text cut!");
}
</script>
Try It
paste event
When you paste text from the clipboard, the browser fires the onpaste event.
Example
<input type="text" onpaste="pasteHandler()">
<script>
function pasteHandler() {
alert("Paste event is fired");
}
</script>
Try It