An event occuring on a webpage is characterised by the user taking some action such as:
- Clicking the mouse
- Scrolling up or down
- Pressing a key on the keyboard
- An input box being changed
- The page load completing
An event occuring on a webpage is characterised by the user taking some action such as:
There are some HTML attributes that you can give to elements to link them to a custom function (which we can
create later). This custom function will be triggered when the conditions of that attribute are met. The syntax
for these are
<element attribute="custom_Function_Name">.
These attributes include:
onmouseover hovering your cursor over the element
onmouseout moving your cursor away from the element
onclick for when you click on an element
These are similar to the
pseudo classes in CSS
such as
:hover
which allows you to add some styling when the element in hovered. But in this case instead of applying styling
we will add our own function. This covers everything you could do in CSS such as changing font size or colour,
but you can also do things such as displaying hidden elements, playing a sound, or validating form input prior
to submission.
It is very important to know that:
| Syntax | Event it tracks |
|---|---|
onclick
|
When a user clicks on the element. |
ondblclick
|
When a user double clicks on the element. |
oncontextmenu
|
When a user right clicks on the element. |
onmousedown
|
When the user presses the mouse click over an element. |
onmouseup
|
When a user releases the mouse click over an element. |
onmouseover or onmouseenter
|
Moving the cursor over an element (onmouseenter does not have event bubbling). |
onmouseout or onmouseleave
|
Moving the cursor off of an element (onmouseleave does not have event bubbling). |
onmousemove
|
Fires continuously as the mouse moves within an element. It does not trigger when the mouse enters or leaves but only when it moves and will fire many times while the mouse is moving. |
The button property of a mouse event returns an integer that represents which mouse button was pressed when the event was triggered.
| Code | Mouse Button |
|---|---|
| 0 | Left mouse button |
| 1 | Middle mouse button |
| 2 | Right mouse button |
You can use this to confirm which mouse button was pressed e.g.
if (event.button == 1) {}
clientX
and
clientY
are properties of the mouse event object that provide the horizontal (clientX) and vertical (clientY)
coordinates of the mouse pointer when the event was triggered. They return the position of the mouse relative
to the viewport (the visible part of the web page). This means the origin (0, 0) is at the top-left corner of
the viewport.
| Syntax | Event it tracks |
|---|---|
onkeydown
|
When a user has pressed a key. |
onkeyup
|
When a user releases the key press. |
oncontextmenu
|
When a user right clicks on the element. |
| For the following, do event.X | |
altKey
|
Returns whether the "alt" key was pressed when the key event was triggered |
charCode
|
Returns the Unicode character code of the key that triggered the event. |
code
|
Returns the code of the key that triggered the event. |
ctrlKey
|
Returns whether the “ctrl” key was pressed when the key event was triggered. |
getModifierState()
|
Returns true if the specified key is activated. |
isComposing
|
Returns whether the state of the event is composing or not. |
key
|
Returns the key value of the key represented by the event. |
keyCode
|
Returns the Unicode character code of the key that triggered the onkeydown or onkeyup event.
|
location
|
Returns the location of a key on the keyboard or device. |
metaKey
|
Returns whether the "meta" key was pressed when the key event was triggered. |
repeat
|
Returns whether a key is being held down repeatedly, or not. |
shiftKey
|
Returns whether the "Shift" key was pressed when the key event was triggered. |
// An example to check which key is pressed
// Add event listener to the whole document looking for a key to be pressed
// And running the custom function keyPressed
document.addEventListener('keydown', keyPressed);
// Custom function keyPressed
function keyPressed(event) {
// Get the key value of the key that was pressed
let keyPressed = event.key;
// Optional continuation:
// Get your HTML element that will display the key press
let keyInfoElement = document.getElementById('key-info');
// Display the key that was pressed
keyInfoElement.innerHTML = `Key pressed: ${keyPressed}`;
}
| Syntax | Event it Tracks |
|---|---|
onchange
|
When the value of an input, select, or textarea changes. |
oninput
|
When the value of a form element is being modified in real-time. |
onsubmit
|
When a form is submitted. |
onreset
|
When a form is reset. |
onfocus
|
When a form element receives focus for example being clicked into. |
onblur
|
When a form element loses focus. |
oninvalid
|
When a form element fails validation. |
To target form values you can do the following:
// Target the element:
let var = document.getElementbyId();
// Then you can log the value
console.log(var.value)
// You can also assign it to a new value
var.value = "newValue"
To capture the submit event you can do the following. Without JavaScript, the page will reload as the data is
submitted to the server, but we can stop it from refreshing with
event.preventDefault();.
// To capture the submit event of a form with an event listener
// Assign the form to a variable
let var = document.getElementById('formId')
// Add an event listener to the form where handleSubmit is a custom function
form.addEventListener('submit', handleSubmit);
// Define the function to handle the submit
function handleSubmit(event) {
event.preventDefault(); // Prevent form from submitting the traditional way
// Example: get the input value and log it
let name = document.getElementById('nameInput').value;
console.log("Form submitted! Name:", name);
// Optional: show an alert
alert("Hello, " + name + "! Form submitted without refreshing the page.");
}
Done in a HTML file this would look like: <form onsubmit="exampleFunction(event);">
and the exampleFunction defined within a script element.
Every form element in HTML has a
submit()
method. In order to submit a form yourself so you do not need to depend on a user you can do whatever
processing you need to and then call
.submit()
in the handler function.
function handleSubmit(event){
// Form processing
formName.submit();
};
| Syntax | Event it Tracks |
|---|---|
DOMContentLoaded
|
The DOM content has finished loading but external assets like images, JS files, CSS files etc have not loaded yet. |
onload
|
When the page or an element (like an image) has finished loading. |
onunload
|
When the user has left the page. |
onresize
|
When the window is resized. |
onscroll
|
When the user scrolls the page or an element. |
onbeforeunload
|
When the user is about to leave a page. This can be used to show a confirmation/warning box. |
| Syntax | Event it Tracks |
|---|---|
oncopy
|
When content is copied. |
oncut
|
When content is cut. |
onpaste
|
When content is pasted. |
Event bubbling is where an event is triggered on an element and it doesn't just stay there, it "bubbles up" the DOM tree, triggering any matching event handlers on parent elements too (unless you explicitly stop it).
onmouseover
does bubble. This means if you have a parent element and child elements inside it, and your mouse moves from
the parent to a child, the onmouseover event will fire again for the child (and potentially also for the parent).
This can lead to multiple, repeated triggers as the mouse moves within nested elements.
onmouseenter
does not bubble. It only fires once when the mouse pointer enters the element it's attached to, even if it then
moves over child elements. It behaves more like the CSS
:hover
pseudo-class. This makes it useful when you only want a single event to occur when the user enters a certain
area.
Functions that you assign to events should include:
Inside the event function, the event is accessibly by the keyword event and the element is accessible by the
keyword
this.
You can set up functions like:
<!--HTML-->
<button id="myButton">Click me!</button>
// JavaScript
document.getElementById('myButton').addEventListener('click', function(event) {
// Log the event type to the console ("click")
console.log('Event type:', event.type);
// Log the element clicked to the console
console.log('Element clicked:', this);
// Change the text in the button
this.textContent = 'Clicked!';
});
Event listeners are a fundamental part of creating interactive web pages using JavaScript. They allow your code to "listen" for specific actions or occurrences such as clicks, key presses, or mouse movements, and run custom logic in response. An event listener is a method that waits for a specified event to occur on a particular DOM element and then executes a block of code known as an event handler. The basic syntax follows:
eventTarget.addEventListener('eventType', eventHandlerFunction);
eventTarget: The DOM element you're watching.'eventType': A string representing the type of event (e.g., 'click', 'keydown', 'submit', 'mouseover').eventHandlerFunction: The function to run when the event is triggered.While it's possible to define the handler inline (as an anonymous function), it's best practice to define your event handler as a separate, named function. This makes your code cleaner, easier to debug, and reusable.
// Define the function first
function boxClicked() {
console.log("Box was clicked!");
}
// Get the element
const box = document.getElementById("click-box");
// Assign the event and function to the element
box.addEventListener("click", boxClicked);
You can remove an event listener using the
.removeEventListener()
method. This is useful for performance optimization or when the listener is no longer needed (e.g., after a
one-time action). You must pass the exact same function reference used in
addEventListener().
// Define the function
function logClick() {
console.log("Clicked");
button.removeEventListener("click", logClick);
}
// Assign the element to a variable
const button = document.getElementById("myBtn");
// Remove the function from the element based on the event
button.addEventListener("click", logClick);
If you have multiple elements that need the same event behaviour, use a loop to assign listeners:
const boxes = document.querySelectorAll(".box");
for (let i = 0; i < boxes.length; i++) {
boxes[i].addEventListener("click", boxClicked);
}
JavaScript stores events as events object which we can access specific things from:
.target: Reference the element that the event is registered to.type: Access the name of the event.timestamp: Access the number of ms between the document loading and the event triggering