JavaScript Event Handling Tutorial with Examples
1. Javascript Events
No ADS
Event is a signal that something has happened. For example, you click on a button, or you close the browser, .. All DOM nodes generate such signals, but there are events other than the DOM for example, your event of closing the browser window.
Below is a list of most useful DOM events:
Mouse Events:
Event | Description |
click | The event occurs when the user clicks on an element |
contextmenu | The event occurs when the user right-clicks on an element to open a context menu |
dblclick | The event occurs when the user double-clicks on an element |
mousedown | The event occurs when the user presses a mouse button over an element |
mouseup | The event occurs when a user releases a mouse button over an element |
mouseenter | The event occurs when the pointer is moved onto an element |
mouseleave | The event occurs when the pointer is moved out of an element |
mousemove | The event occurs when the pointer is moving while it is over an element |
mouseout | The event occurs when a user moves the mouse pointer out of an element, or out of one of its children |
mouseover | The event occurs when the pointer is moved onto an element, or onto one of its children |
Form elements events:
Event | Description |
submit | When user submit a <form>. |
focus | When user focus on an Element, for example <input>. |
blur | When user leaves an Element, for example <input>. |
Keyboard Events:
Event | Description |
keydown | The event occurs when the user is pressing a key |
keyup | The event occurs when the user releases a key |
keypress | The event occurs when the user presses a key. (Complete 2 actions, press down and release). |
Document Events.
Event | Description |
DOMContentLoaded | When HTML content has loaded and processed. The DOM model has been created completely. |
CSS Events:
Event | Description |
animationstart | The event occurs when a CSS animation has started |
animationend | The event occurs when a CSS animation has completed |
animationiteration | The event occurs when a CSS animation is repeated |
Event Handling:
To handle the event, you need to attach the event to a handler. the handler can be a function. When the event occurs the handler will be called to operate. The handler is a way for running Javascript codes that corresponds to user's actions.
The handler can be set in the HTML with the on{event} attribute. For example, click event:
<input value="Click me" onclick="alert('Click!')" type="button">
<input value="Click me" onclick="someFunction()" type="button">
The this object represents for the element generating the event.
<input value="Click me" onclick="someFunction(this)" type="button">
When the event occurs, Javascript creates theevent object and you can use it as a value of parameter.
<input value="Click me" onclick="someFunction(event)" type="button">
You can also access the event generating event through the event object.
var target = event.target;
2. Example with events
No ADS
Simple and often encountered event is the event that users click on an element. Below is a simple example. The user clicks the "=" button to sum two numbers.
onclick-example.html
<!DOCTYPE html>
<html>
<head>
<title>Hello Javascript</title>
<script type = "text/javascript">
function doCalculate() {
var a = document.getElementById("a").value; // A String value
var b = document.getElementById("b").value; // A String value
var c = Number(a) + Number(b);
document.getElementById("c").value = c;
}
</script>
</head>
<body>
<h3>Click Event example</h3>
<input id = "a" type="text" value= "100"/> <br/>
+ <br/>
<input id = "b" type="text" value = "200"/> <br/>
<button onclick="doCalculate()"> = </button> <br/>
<input id = "c" type="text" value = ""/>
</body>
</html>
-
The this object is the element that emits the event. You can pass this object into the event handling function.
this-obj-example.html
<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
<script type = "text/javascript">
function changeSize(target) {
var random = Math.round(Math.random() * 100) + 200;
target.style.width = random + "px";
target.style.height = random + "px";
}
</script>
</head>
<body>
<h3>Event with 'this' object</h3>
<button onclick="changeSize(this)">Click Me to Change Size</button>
</body>
</html>
-
When the event occurs, an event object is created by Javascript. it contains tje information related to the event. For example, for the mouse event, the event object may contain the information such as the mouse position relative to the browser, the position of mouse relative to the element that emits the event, ... You can use the event object to pass in the event handling function.
<input value="Click me" onclick="someFunction(event)" type="button">
mouse-events-example.html
<!DOCTYPE html>
<html>
<head>
<title>Javascript Mouse Events</title>
<script src="mouse-events-example.js"></script>
<style>
.my-div {
width: 290px;
height: 100px;
background: blue;
}
</style>
</head>
<body>
<h3>Mouse Events (Enter, Move, Leave)</h3>
<div class="my-div"
onmouseenter="mouseenterHandler(event)"
onmouseleave="mouseleaveHandler(event)"
onmousemove="mousemoveHandler(event)">
</div>
<h3>Mouse position</h3>
<div style="color:red;" id="position-div">
</div>
<h3>Statistics</h3>
<div style="color:red;" id="statistics-div">
</div>
</body>
</html>
mouse-events-example.js
var enterCount = 0;
var moveCount = 0;
var leaveCount = 0;
function mouseleaveHandler(evt) {
leaveCount += 1;
showPosition(evt);
showStatistics();
}
function mouseenterHandler(evt) {
enterCount += 1;
showPosition(evt);
showStatistics();
}
function mousemoveHandler(evt) {
moveCount += 1;
showPosition(evt);
showStatistics();
}
function showPosition(evt) {
var html = "offsetX: " + evt.offsetX +"<br/>" //
+
"offsetY: " + evt.offsetY;
document.getElementById("position-div").innerHTML = html;
}
function showStatistics() {
var html =
"enterCount:" + enterCount + "<br/>" //
+
"moveCount:" + moveCount + "<br/>" //
+
"leaveCount:" + leaveCount;
document.getElementById("statistics-div").innerHTML = html;
}
-
You can access the element emitting event via the event object.
event-obj-example.html
<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
<script type = "text/javascript">
function changeSize(evt) {
var target = evt.target;
var random = Math.round(Math.random() * 100) + 100;
target.style.width = random + "px";
target.style.height = random + "px";
}
</script>
</head>
<body>
<h3>Access 'target' object via 'event' object</h3>
<button onclick="changeSize(event)">Click Me to Change Size</button>
</body>
</html>
-
Example of a handler with multiple parameters.
multi-params-example.html
<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
<script type = "text/javascript">
function changeSize(borderColor, target, evt, bgColor) {
var random = Math.round(Math.random() * 100) + 100;
target.style.width = random + "px";
target.style.height = random + "px";
target.style.borderColor = borderColor;
target.style.backgroundColor = bgColor;
}
</script>
</head>
<body>
<h3>A Handler has multiple parameters</h3>
<a href="">Reset</a> <br/><br/>
<button onclick="changeSize('red', this, event, 'green')">Click Me</button>
</body>
</html>
No ADS
ECMAScript, Javascript Tutorials
- Javascript Screen Tutorial with Examples
- Javascript MouseEvent Tutorial with Examples
- Javascript XMLHttpRequest Tutorial with Examples
- JavaScript if else Statement Tutorial with Examples
- JavaScript Promise, Async/Await Tutorial with Examples
- Javascript History API Tutorial with Examples
- Javascript Menubar Tutorial with Examples
- Javascript Location Tutorial with Examples
- JavaScript Boolean Tutorial with Examples
- JavaScript setTimeout and setInterval Function
- Javascript FocusEvent Tutorial with Examples
- JavaScript Functions Tutorial with Examples
- Introduction to Javascript HTML5 Canvas API
- Javascript Navigator Tutorial with Examples
- Javascript URL Encoding Tutorial with Examples
- JavaScript Variables Tutorial with Examples
- Javascript InputEvent Tutorial with Examples
- Javascript HashChangeEvent Tutorial with Examples
- Introduction to Javascript and ECMAScript
- Javascript Window Tutorial with Examples
- Alert, Confirm, Prompt Dialog Box in Javascript
- Javascript WheelEvent Tutorial with Examples
- JavaScript Switch Statement
- Javascript Locationbar Tutorial with Examples
- Highlighting code with SyntaxHighlighter Javascript library
- What are polyfills in programming science?
- Class and inheritance simulation techniques in JavaScript
- Bitwise Operations
- Javascript Geolocation API Tutorial with Examples
- JavaScript Symbols Tutorial with Examples
- Javascript FileReader Tutorial with Examples
- JavaScript JSON Tutorial with Examples
- JavaScript Date Tutorial with Examples
- JavaScript Map Collection Tutorial with Examples
- Javascript Console Tutorial with Examples
- JavaScript Strings Tutorial with Examples
- JavaScript Modules Tutorial with Examples
- Javascript Form Validation Tutorial with Examples
- Javascript ChangeEvent Tutorial with Examples
- JavaScript Number Tutorial with Examples
- The History of Modules in JavaScript
- Javascript Statusbar Tutorial with Examples
- Undertanding JavaScript Iterables and Iterators
- Quickstart with Javascript
- JavaScript Event Handling Tutorial with Examples
- JavaScript void Keyword Tutorial with Examples
- Classes and Objects in JavaScript
- JavaScript Set Collection Tutorial with Examples
- Javascript DragEvent Tutorial with Examples
- JavaScript Loops Tutorial with Examples
- Inheritance and polymorphism in JavaScript
- Javascript Scrollbars Tutorial with Examples
- Parsing XML in Javascript with DOMParser
- Quickstart with JavaScript
- JavaScript Web Cookies Tutorial with Examples
- Javascript KeyboardEvent Tutorial with Examples
- Javascript Fetch API Tutorial with Examples
- JavaScript Error Handling Tutorial with Examples
- Undertanding Duck Typing in JavaScript
- JavaScript Arrays Tutorial with Examples
- JavaScript Regular Expressions Tutorial with Examples
Show More