Event delegation in JavaScript is a technique that allows us to attach a single event listener to a parent element, and then use the event object to determine which child element triggered the event. This way, we can handle multiple events with a single event listener, and avoid adding too many event listeners to the DOM.
Steps of Event Delegation
1. Attach a Listener to a Common Ancestor
Attach a single event listener to a parent element, encapsulating the elements you wish to monitor; this is in lieu of attaching individual event listeners for each element. Use methods such as addEventListener for efficient implementation.
2. Check the Target Element
Inspect the event.target property within the event handler to pinpoint the specific element that triggered it in its common ancestor. Common checks involve scrutinizing tagName, classList, or other target element properties.
3. Perform the Desired Action
Based on the identified target element and any specified criteria, execute the desired action or functionality. This could involve modifying content, handling a button click, or performing any custom logic associated with the event.
Event Delegation Examples
Example: List Item Clicks
In this example, we employ event delegation to adeptly manage clicks on a dynamically changing list of tutorials. The <ul> element serving as the shared ancestor for all list items has one solitary event listener attached to it.
Upon clicking a tutorial, an <li> identifies itself as the target via our skilfully crafted event handler; consequently, enabling logging of that particular tutorial’s content in the console. This demonstrates the streamlined and scalable approach of event delegation in managing dynamic lists.
Employing event delegation here allows for the monitoring and logging of changes in form control values: the <form> element acts as a common ancestor, while an input event listener captures alterations within input fields. The script confirms by examining the target element within its handler, that events are indeed related to an <input>. The message, consequently, logs the modified input’s name and new value: this action not only showcases event delegation’s adaptability but also its efficiency in managing dynamic form interactions.
Event delegation is valuable in scenarios where a single event listener can efficiently manage interactions for multiple elements, reducing redundancy and improving performance. Common use cases include handling dynamic lists, form interactions, table actions, accordion or tabbed interfaces, tree structures, dropdown menus, multi-step wizards, carousels, and various interactive UI components. It simplifies code structure, ensures consistency, and adapts well to dynamic content changes, making it a versatile technique in web development.
JavaScript window events are actions that occur when the user does something affecting the entire browser window, like loading, resizing, closing, or moving the window. The most common window event is simply loading the window by opening a particular web page. This event is handled by the onload event handler.
Developers can use JavaScript to create dynamic, interactive web pages that respond to user actions. The interactivity depends on two core aspects: window events and document events. Operating at the browser’s panoramic level, window events bestow control over the overall state of the browser window; alternatively, document events interact with the HTML document, empowering developers to react specifically towards elements or actions within a page
Window Events
At the browser level, window events happen and hold association with the window object; this global object represents the web browser’s window. Frequently employed to oversee the overall state of a browser window or manage global interactions are these types of events.
Event Name
Description
load
Triggered when the entire web page, including all its resources, has finished loading.
unload
Fired when the user is leaving the page or closing the browser window or tab.
resize
Activated when the size of the browser window is changed.
scroll
Fired when the user scrolls the page.
Example: Demonstrating Window Events
In this example, a script actively listens for the ‘load,’ ‘resize,’ and ‘scroll’ events on the window; it includes an initial page load alert to inform users that loading is complete. Should they subsequently resize their window, an alert will trigger thereby displaying the new size of their updated viewport. Moreover, when the user scrolls on the page, an alert is triggered to indicate their action.
window.addEventListener('resize',function(){var newSizeInfo ='New window size: '+ window.innerWidth +' x '+ window.innerHeight;
document.getElementById('resizeInfo').innerText = newSizeInfo;alert("Page has been resized");});
window.addEventListener('scroll',function(){alert('You have scrolled on this page.');},{once:true});</script></head><body><div id="resizeInfo">Initial window size: ${window.innerWidth} x ${window.innerHeight}</div></body></html></pre>
Document Events
Document events on the other hand occur at the level of the HTML document within the window and are associated with the document object which represents the HTML document thereby providing an interface to interact with the content of the page.
Event Name
Description
DOMContentLoaded
Triggered when the HTML document has been completely loaded and parsed, without waiting for external resources like images.
click
Fired when the user clicks on an element.
submit
Triggered when a form is submitted.
keydown/keyup/keypress
These events are triggered when a key is pressed, released, or both, respectively.
change
Fired when the value of an input element changes, such as with text inputs or dropdowns.
Example: Demonstrating Document Events
In this example, we've included a script that listens for the 'DOMContentLoaded,' 'click,' 'submit,' and 'keydown' events on the document. Upon the 'DOMContentLoaded' event, it logs to the console that the DOM content has been fully loaded. Subsequently, clicking an element triggers an alert displaying the tag name of the clicked element. Submitting a form also alerts that the form has been submitted. Furthermore, pressing a key like entering the username with characters, alerts every keypress to the screen.
The form events in JavaScript are events that are associated with HTML forms. These events are triggered by user actions when interacting with form elements like text fields, buttons, checkboxes, etc. Form events allow you to execute JavaScript code in response to these actions, enabling you to validate form data, perform actions on form submission or reset, and enhance the user experience.
JavaScript form events are hooked onto the elements in the Document Object Model also known as DOM where by default the bubbling propagation is used i.e. from bottom (children) to top(parent).
List of Common Form Events
Here are some common form events:
Form Event
Description
onsubmit
Triggered when a form is submitted. It’s often used for form validation before data is sent to the server.
onreset
Triggered when the form is reset, allowing you to perform actions when the user resets the form.
onchange
Triggered when the value of a form element (input, select, textarea) changes. Commonly used for user input validation or dynamic updates.
oninput
Triggered immediately when the value of an input element changes, allowing for real-time handling of user input.
onfocus
Triggered when an element receives focus, such as when a user clicks or tabs into an input field. Useful for providing feedback or enhancing the user experience.
onblur
Triggered when an element loses focus, such as when a user clicks outside an input field or tabs away. Useful for validation or updates triggered by loss of focus.
Examples
Example: The onchange Event
The provided instance below illustrates the functionality of the onchange event. This event activates upon a user’s alteration in dropdown (<select>) option selection. The function, handleChange, dynamically modifies an <h2> element to display the newly selected country; thus offering immediate feedback as user preferences evolve.
<!DOCTYPE html><html><body><label for="country">Select a country:</label><select id="country" onchange="handleChange()"><option value="USA">USA</option><option value="Canada">Canada</option><option value="UK">UK</option><option value="India">India</option></select><p id="txt"></p><script>functionhandleChange(){// Perform actions when the dropdown selection changesvar selectedCountry = document.getElementById('country').value;
The following example highlights the onsubmit event's functionality upon form submission. The form features a username field and password field; both must be filled for successful validation when invoking the validateForm function. Upon passing this validation, submitting the form will trigger display of a confirmation message.
<!DOCTYPE html><html><body><form onsubmit="return validateForm()"><label for="username">Username:</label><input type="text" id="username" name="username" required><label for="password">Password:</label><input type="password" id="password" name="password" required><br/><input type="submit" value="Submit"></form><script>functionvalidateForm(){var username = document.getElementById('username').value;var password = document.getElementById('password').value;// Perform validationif(username ===""|| password ===""){alert("Please fill in all fields");returnfalse;// Prevent form submission}alert("Form submitted! Username is:"+username+",Password is:"+password);returntrue;// Allow form submission}</script></body></html>
Example: The onreset event
In this demonstration, we observe the onreset event in action: it triggers upon the user's click of the "Reset" button within a form. The resetForm function once invoked, clears the form content filled by user and then displays an alert to confirm successful reset of said form.
<!DOCTYPE html><html><body><form onreset="resetForm()"><label for="email">Email:</label><input type="email" id="email" name="email" required><input type="reset" value="Reset"></form><script>functionresetForm(){// Perform actions when the form is resetalert("Form has been reset!");}</script></body></html>
Example: The oninput Event
This example illustrates the oninput event: as the user types into the search input field a real-time action, indeed! The handleInput function triggers; it logs each current search input directly to screen.
The onfocus and onblur events merge in this example. The user's focus on the input field triggers a call to the handleFocus function, which then logs a message into the console. In contrast, when clicks outside of or tabs away from said input field this action triggers execution of another function called handleBlur that subsequently records an alternative message within that same console log.
<!DOCTYPE html><html><body><label for="name">Name:</label><input type="text" id="name" onfocus="handleFocus()" onblur="handleBlur()"><p id="output"></p><script>const output = document.getElementById('output');functionhandleFocus(){// Perform actions when the input gets focus
output.innerHTML +="Input has focus"+"<br>";}functionhandleBlur(){// Perform actions when the input loses focus
output.innerHTML +="Input lost focus"+"<br>";}</script></body></html></pre>
The keyboard events in JavaScript provide a way to interact with a web page or application based on the user’s keyboard input. These events allow developers to capture and respond to various keyboard actions, such as key presses, key releases, and character inputs. The primary keyboard events in JavaScript include keydown, keypress, and keyup.
Common Keyboard Events
Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown event. This event equips developers with information about the specific key that was pressed: this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or Alt were also depressed.
Keypress Event − The keypress event triggers when a user types an actual character. Non-character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it to capture user input for form fields or create interactive typing features.
Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of a keyup event; this particular event proves beneficial in tracking specific keys’ releases and subsequently implementing actions, thereby creating an interactive user experience.
Keyboard Event Properties
For keyboard events in JavaScript, several properties are commonly used to gather information about the key pressed. Here are some key properties specifically relevant to keyboard events −
Property
Description
event.key
String representing the key value of the pressed key.
event.code
String representing the physical key on the keyboard.
event.location
Integer indicating the location of the key on the keyboard.
event.ctrlKey
Boolean indicating whether the Ctrl key was held down.
event.shiftKey
Boolean indicating whether the Shift key was held down.
event.altKey
Boolean indicating whether the Alt key was held down.
event.metaKey
Boolean indicating whether the Meta (Command) key was held down.
event.repeat
Boolean indicating whether the key event is a repeat event.
event.isComposing
Boolean indicating whether the event is part of a composition of multiple keystrokes.
event.which
Deprecated property; previously used to identify the numeric key code.
event.getModifierState(keyArg)
Method that returns a boolean indicating whether the modifier key is pressed.
Example: Keydown Event
This example illustrates the application of JavaScript’s keydown event. The event listener seizes the keydown event upon pressing any key, displaying in an HTML element identified as “output” – its corresponding key (an event property).
<!DOCTYPE html><html><body><h3>Press any key</h3><script>
In this example, the keypress event is utilized to capture a typed character. When a character is typed, the event listener triggers, and the character is displayed in the HTML element with the id "output".
<!DOCTYPE html><html><body><h3>Type a character</h3><div id="output"></div><script>
The keyup event is showcased in this example. It captures the event when a key is released after being pressed. The released key is then displayed on screen.
<!DOCTYPE html><html><body><h3>Press and Release a key</h3><div id="output"></div><script>
There is a difference between keydown and keypress. keydown is triggered when any key is pressed down, providing information about the pressed key, including modifiers. keypress is triggered specifically when a character key is pressed, providing information about the typed character without details on modifiers. Keydown fires continuously as long as the key is held down.
In all the above examples, we have used the addEventListener but these events can be listened to without this function as well. This is because of you can assign event handlers directly to specific properties. However, keep in mind that using addEventListener is generally considered a better practice because it allows you to attach multiple event handlers to the same event, and it separates JavaScript logic from the HTML structure.
Example: Without using addEventListener method
In this example, we have an input box. When it detects a keydown event (onkeydown), the handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the handleKeyUp function. Both the functions print appropriate messages to the screen.
<!DOCTYPE html><html><body><div>Enter some text:<input onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)"></div><div id="output"></div><script>functionhandleKeyDown(event){
JavaScript mouse events allow users to control and interact with web pages using their mouse. These events trigger specific functions or actions in response to user clicks, scrolls, drags, and other mouse movements.
To handle mouse events in JavaScript, you can use the addEventListener() method. The addEventListener() method takes two arguments: the event type and the event handler function. The event type is the name of the event that you want to handle, and the event handler function is the function that will be called when the event occurs.
In web development, JavaScript provides a powerful mechanism to respond to user interactions with the mouse through a set of events. These events enable developers to create dynamic and interactive web applications by capturing and handling various mouse-related actions.
Common Mouse Events
Following are the most common JavaScript mouse events:
Mouse Event
Description
Click
When an element experiences the press of a mouse button, it triggers the click event.
Double Click
The dblclick event fires upon the rapid double-clicking of a mouse button.
Mouse Down and Mouse Up
The initiation of a mouse click triggers the ‘mousedown’ event, while the completion of that click causes the ‘mouseup’ event to occur.
Mouse Move
When the mouse pointer moves over an element, it triggers the ‘mousemove’ event; this event supplies developers with positional information about the mouse. This data empowers them to devise responsive interfaces that are rooted in dynamic mouse movements.
Context Menu
When the user attempts to open the context menu, typically by right-clicking, they trigger the contextmenu event. This event allows developers to customize or inhibit default behaviour of the context menu.
Wheel
When the mouse wheel rotates, it fires the ‘wheel event’; this particular event commonly manifests in implementing features, notably zooming or scrolling.
Drag and Drop
Events like dragstart, dragend, dragover, dragenter, dragleave, and drop are associated with drag-and-drop functionality. They allow developers to create interactive interfaces for dragging elements within a web page.
Example : Click Event
In this example we demonstrate the click event. When the button is clicked, it prints an appropriate message to the console message i.e. Clicked!. This event is often used while submitting forms.
The dblclick event operates in this example, triggering upon a double-click of the designated button. We attach the event listener to an element with "doubleClickButton" as its id. A user's double-click on the button prompts a function that logs a console message, confirming their interaction with it.
The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as "mouseUpDownDiv." Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up.
<!DOCTYPE html><html><head><title>Mouse Down and Mouse Up Events Example</title></head><body><div id="mouseUpDownDiv"
style="width: 600px; height: 100px; background-color: lightblue;">
Please perform mouse down and up event any where inthisDIV.</div><p id ="output"></p><script>const mouseUpDownDiv = document.getElementById('mouseUpDownDiv');const outputDiv = document.getElementById("output");
In this instance, we employ the mousemove event to monitor the mouse pointer's movement over a specific <div> element identified as "mouseMoveDiv." The handler function extracts clientX and clientY properties from an event object that represents X-Y coordinates of said pointer. Subsequently, these are logged into console; thus offering real-time feedback on where exactly within our designated div area is the user positioning their cursor.
mouseMoveDiv.addEventListener('mousemove',function(event){const x = event.clientX;const y = event.clientY;
outputDiv.innerHTML +=Mouse moved to (${x}, ${y})+JSON.stringify(event)+"<br>";});</script></body></html></pre>
Example: Wheel Event
This example showcases the wheel event, activated when the mouse wheel is rotated. The event listener is attached to a <div> element with the id "wheelDiv." When the user rotates the mouse wheel over this div, the associated function logs a message to the console, indicating that the mouse wheel has been rotated.
<!DOCTYPE html><html><head><title>Wheel Event Example</title></head><body><div id="wheelDiv"
style="width: 600px; height: 200px; background-color: palevioletred;">
Please bring the curser inside thisDIV and rotate the wheel of mouse.</div><p id ="output"></p><script>const wheelDiv = document.getElementById('wheelDiv');const outputDiv = document.getElementById("output");
The JavaScript addEventListener() method is used to attach an event handler function to an HTML element. This allows you to specify a function that will be executed when a particular event occurs on the specified element.
Events are a specific occurrence or action like user clicks, keypress or page loads. The browser detects these events and triggers associated JavaScript functions known as event handlers to respond accordingly.
Developers employ the ‘addEventListener()’ method for linking particular HTML elements with specific function behaviours when those events occur. Examples of events include clicks, mouse movements, keyboard inputs, and document loading.
Syntax
The basic syntax for addEventListener() is as follows −
Here element is an HTML element, such as a button, input or div – can be selected using methods like getElementById, getElementsByClassName, getElementsByTagName and querySelector; these are just a few examples. The event listener attaches to this particular element.
Parameters
The addEventListener() method accepts the following parameters −
event − a string that embodies the type of action − for instance, “click”, “mouseover”, or “keydown” among others; will serve as our trigger to execute the given function.
function − a named, anonymous or reference to an existing function is called when the specified event occurs; it’s essentially the operation that facilitates execution at predetermined instances.
options (optional) − it allows for the specification of additional settings particularly capturing or once behaviours related to the event listener.
Examples
Example: Alert on Clicking Button
In this example, we will have a simple button being displayed which upon clicking shows an alert on the screen. The addeventlistener will be responsible for handling the event click which means it will call a function handleClick which throws an alert to the screen when the button is clicked. We make use of the getElementById to fetch the button we want to bind the event listener to.
This is a commonly used event when it comes to submitting on forms, login, signup etc.
<html><head><title>Click Event Example</title></head><body><p> Click the button below to perform an event </p><button id="myButton">Click Me</button><script>// Get the button elementconst button = document.getElementById("myButton");// Define the event handler functionfunctionhandleClick(){alert("Button clicked!");}// Attach the event listener to the button
In this example we have a dig tag which will initially be of light blue colour. Upon hovering the mouse on this div tag, it will change to red and back to blue if we hover out.
There are two events in this case, mouseover and mouseout. The mouseover means the mouse moves onto an element mouseout means the mouse movies out of an element.
There are two functions here, one for mouseover and one for mouseout. Upon mouseover, the background colour property is set to light coral (a shade of red) and upon mouseout, the background colour is set to light blue.
These types of mouse hover events are commonly seen when hovering over the navbar of a lot of websites.
#myDiv {
width:600px;
height:200px;
background-color: lightblue;}</style></head><body><div id="myDiv">Hover over me</div><script>// Get the div elementconst myDiv = document.getElementById("myDiv");// Define the event handler functionfunctionhandleMouseover(){
myDiv.style.backgroundColor ="lightcoral";}// Attach the event listener to the div
myDiv.addEventListener("mouseover", handleMouseover);// Additional example: Change color back on mouseoutfunctionhandleMouseout(){
myDiv.style.backgroundColor ="lightblue";}
There can be multiple event listeners for the same elements like in the case of 2nd example which has two event listeners (for mouseover and mouseout). Event listeners can be removed using the removeEventListener function. By passing a parameter in the options as once:true, we can ensure that the event listener is removed after being invoked once and this is important in certain case scenarios like payments.
It is important to note that one should never use the "on" prefix for specifying events, this simply means for a click event, we should specify it as "click" and not "onclick".
The DOM events are actions that can be performed on HTML elements. When an event occurs, it triggers a JavaScript function. This function can then be used to change the HTML element or perform other actions.
Here are some examples of DOM events:
Click − This event occurs when a user clicks on an HTML element.
Load − This event occurs when an HTML element is loaded.
Change − This event occurs when the value of an HTML element is changed.
Submit − This event occurs when an HTML form is submitted.
You can use the event handlers or addEventListener() method to listen to and react to the DOM events. The addEventListener() method takes two arguments: the name of the event and the function that you want to be called when the event occurs.
The DOM events are also referred as Document Object Model events. It is used to interact with the DOM elements and manipulate the DOM elements from JavaScript when any event occurs.
Let’s look at the below examples of DOM events.
The onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html><head><script>functionsayHello(){alert("Hello World")}</script></head><body><p>Click the following button and see result</p><form><input type ="button" onclick ="sayHello()" value ="Say Hello"/></form></body></html>
The ondblclick Event Type
We use the ‘ondblclick’ event handler in the code below with the element. When users double click the button, it calls the changeColor() function.
In the changeColor() function, we change the color of the text. So, the code will change the text’s color when the user double-clicks the button.
Example
<html><body><h2 id ="text"> Hi Users!</h2><button ondblclick="changeColor()"> Double click me!</button><script>functionchangeColor(){
We used the 'keydown' event in the code below with the <input> element. Whenever the user will press any key, it will call the customizeInput() function.
In the customizeInput() function, we change the background color of the input and the input text to red.
Example
<html><body><p> Enter charater/s by pressing any key </p><input type ="text" onkeydown ="customizeInput()"><script>functioncustomizeInput(){var ele = document.getElementsByTagName("INPUT")[0];
JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference.
JavaScript Event Handlers
Event handler can be used as an attribute of the HTML element. It takes the inline JavaScript or function execution code as a value.
Whenever any event triggers, it invokes the inline JavaScript code or executes the callback function to perform the particular action.
In simple terms, it is used to handle the events.
Syntax
Users can follow the syntax below to use event handlers with HTML elements.
<div eventHandler ="JavaScript_code"></div>
In the above syntax, you need to replace the ‘eventHandler’ with the actual event handler like ‘onclick’, ‘onmouseover’, etc. The ‘JavaScript_code’ should execute the function or run JavaScript inline.
Example: Inline JavaScript with Event Handlers
In the code below, we have created the <button> element. Also, we have used the ‘onclick’ event handler to capture the click event on the button.
We have written the inline JavaScript code to handle the event. In the inline JavaScript code, the ‘this’ keyword represents the <button> element, and we change the button’s text color to red.
<html><body><h2> Click the button to Change its text's color </h2><button onclick ="this.style.color='red'"> Click Me </button><div id ="output"></div></body></html>
Example: Function with Event Handlers
In the code below, we have created the <div> element and given style into the <head> section.
We used the ‘onclick’ event handler with the <button> element, which calls the handleClick() function when the user clicks the button.
The handleClick() function takes the ‘event’ object as a parameter. In the handleClick() function, we change the background color of the <div> element using JavaScript.
<html><head><style>
#test {
width:600px;
height:100px;
background-color: red;}</style></head><body><div id ="test"></div><br><button onclick ="handleClick()"> Change Div Color </button><script>functionhandleClick(event){var div = document.getElementById("test");
div.style.backgroundColor ="blue";}</script></body></html></pre>
Example: Multiple Functions with Event Handlers
In the code below, we have added the 'ommouseenter' event handler with the <div> element. We call the changeFontSize() and changeColor() functions when a user enters the mouse cursor in the <div> element.
The changeFontSize() function changes the size of the text, and changeColor() function changes the color of the text.
This way, you can invoke the multiple functions on the particular event.
<html><head><style>
#test {
font-size:15px;}</style></head><body><h2> Hover over the below text to customize the font.</h2><div id ="test" onmouseenter ="changeFontSize(); changeColor();"> Hello World!</div><br><script>functionchangeFontSize(event){
document.getElementById("test").style.fontSize ="25px";}functionchangeColor(event){
document.getElementById("test").style.color ="red";}</script></body></html></pre>
JavaScript Event Object
The function that handles the event takes the 'event' object as a parameter. The 'event' object contains the information about the event and the element on which it occurred.
There are various properties and methods are also available which can be used with the event object to get information.
Object
Description
Event
It is a parent of all event objects.
Here is the list of different types of event objects. Each event object contains various events, methods, and properties.
Object/Type
Handles
AnimationEvent
It handles the CSS animations.
ClipboardEvent
It handles the changes of the clipboard.
DragEvent
It handles the drag-and-drop events.
FocusEvent
To handle the focus events.
HashChangeEvent
It handles the changes in the anchor part of the URL.
InputEvent
To handle the form inputs.
KeyboardEvent
To handle the keyboard interaction by users.
MediaEvent
It handles the media-related events.
MouseEvent
To handle the mouse interaction by users.
PageTransitionEvent
To handle the navigation between web pages.
PopStateEvent
It handles the changes in the page history.
ProgressEvent
To handle the progress of the file loading.
StorageEvent
To handle changes in the web storage.
TouchEvent
To handle touch interaction on the devices screen.
TransitionEvent
To handle CSS transition.
UiEvent
To handle the user interface interaction by users.
The Geolocation API is a web API that provides a JavaScript interface to access the user’s geographical location data. A Geolocation API contains the various methods and properties that you can use to access the user’s location on your website.
It detects the location of the user’s using the device’s GPS. The accuracy of the location depends on the accuracy of the GPS device.
As location compromises the users’ privacy, it asks for permission before accessing the location. If users grant permission, websites can access the latitude, longitude, etc.
Sometimes, developers need to get the user’s location on the website. For example, if you are creating an Ola, Uber, etc. type applications, you need to know the user’s location to pick them up for the ride.
The Geolocation API allows users to share the location with a particular website.
Real-time use cases of the Geolocation API
Here are the real-time use cases of the Geolocation API.
To get the user’s location coordinates, show them on the map.
To tag the user’s location on the photograph.
To suggest nearby stores, food courts, petrol pumps, etc., to users.
To get the current location for the product or food delivery.
To pick up users for the ride from their current location.
Using the Geolocation API
To use the Geolocation API, you can use the ‘navigator’ property of the window object. The Navigator object contains the ‘geolocation’ property, containing the various properties and methods to manipulate the user’s location.
Syntax
Follow the syntax below to use the Geolocation API.
var geolocation = window.navigator.geolocation;ORvar geolocation = navigator.geolocation;
Here, the geolocation object allows you to access the location coordinates.
Example: Checking the browser support
Using the navigator, you can check whether the user’s browser supports the Geolocation.geolocation property.
The code below prints the message accordingly whether the Geolocation is supported.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><div id ="output"></div><script>const output = document.getElementById("output");if(navigator.geolocation){
output.innerHTML +="Geolocation is supported by your browser."}else{
output.innerHTML +="Geolocation is not supported by your browser."}</script></body></html></pre>
Output
Geolocation is supported by your browser.
Geolocation Methods
Here are the methods of the Geolocation API.
Method
Description
getCurrentPosition()
It is used to retrieve the current geographic location of the website user.
watchPosition()
It is used to update the user's live location continuously.
clearWatch()
To clear the ongoing watch of the user's location using the watchPosition() method.
The Location Properties
The getCurrentPosition() method executes the callback function you passed as an argument. The callback function takes the object as a parameter. The parametric object contains various properties with information about the user's location.
Here, we have listed all properties of the location object in the table below.
Property
Type
Description
coords
objects
It is an object you get as a parameter of the callback function of the getCurrentPosition() method. It contains the below properties.
coords.latitude
Number
It contains the latitude of the current location in decimal degrees. The value range is [-90.00, +90.00].
coords.longitude
Number
It contains the longitude of the current location in decimal degrees. The value range is [-180.00, +180.00].
coords.altitude
Number
It is an optional property, and it specifies the altitude estimate in meters above the WGS 84 ellipsoid.
coords.accuracy
Number
It is also optional and contains the accuracy of the latitude and longitude estimates in meters.
coords.altitudeAccuracy
Number
[Optional]. It contains the accuracy of the altitude estimate in meters.
coords.heading
Number
[Optional]. It contains information about the device's current direction of movement in degrees counting clockwise relative to true north.
coords.speed
Number
[Optional]. It contains the device's current ground speed in meters per second.
timestamp
date
It contains the information about the time when the location information was retrieved, and the Position object created.
Getting User's Location
You can use the getCurrentPosition() method to get the user's current location.
Syntax
Users can follow the syntax below to get the user's current position using the getCurrentPosition() method.
The getCurrentPosition() object takes 3 parameters.
successCallback − This function will be called when the method successfully retrieves the user's location.
errorCallback − This function will be called when the method throws an error while accessing the user's location.
Options − It is an optional parameter. It is an object containing properties like timeout, maxAge, etc.
Permitting the website to access your location
Whenever any website tries to access your location, the browser pops up the permission alert box. If you click the 'allow, it can fetch your location details. Otherwise, it throws an error.
You can see the permission pop-up in the image below.
Example
In the below code, we use the getCurrentPosition() method to get the user's location. The method calls the getCords() function to get the current location.
In the getCords() function, we print the value of the various properties of the cords object.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><h3> Location Information </h3><button onclick ="findLocation()"> Find Location </button><p id ="output"></p><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(getCords);//}else{
output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
output.innerHTML +="The current position is: <br>";
output.innerHTML +="Latitude: "+ coords.coords.latitude +"<br>";
output.innerHTML +="Longitude: "+ coords.coords.longitude +"<br>";
output.innerHTML +="Accuracy: "+ coords.coords.accuracy +"<br>";
output.innerHTML +="Altitude: "+ coords.coords.altitude +"<br>";}</script></body></html></pre>
Geolocation Errors
The getCurrentPosition() method takes the callback function as a second parameter to handle the error. The callback function can have an error object as a parameter.
In the below cases, an error can occur.
When the user has denied access to the location.
When location information is not available.
When the request for the location is timed out.
It can also generate any random error.
Here is the list of properties of the error object.
Property
Type
Description
code
Number
It contains the error code.
message
String
It contains the error message.
Here is the list of different error codes.
Code
Constant
Description
0
UNKNOWN_ERROR
When methods of the geolocation object cant retrieve the location, it returns the code 0 for unknown error.
1
PERMISSION_DENIED
When the user has denied the permission to access the location.
2
POSITION_UNAVAILABLE
When it cant find the location of the device.
3
TIMEOUT
When the method of the geolocation object cant find the users position.
Example: Error Handling
We use the getCurrentPosition() method in the findLocation() function in the below code. We have passed the errorCallback() function as a second parameter of the getCurrentPosition() method to handle the errors.
In the errorCallback() function, we use the switch case statement to print the different error messages based on the error code.
When you click the Find Location button, it will show you a pop-up asking permission to access the location. If you click on the 'block, it will show you an error.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
navigator.geolocation.getCurrentPosition(getCords, errorCallback);//}else{
output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
output.innerHTML +="The current position is: <br>";
output.innerHTML +="Latitude: "+ coords.coords.latitude +"<br>";
output.innerHTML +="Longitude: "+ coords.coords.longitude +"<br>";}// Function to handle errorfunctionerrorCallback(err){switch(err.code){case err.PERMISSION_DENIED:
output.innerHTML +="You have denied to access your device's location";break;case err.POSITION_UNAVAILABLE:
output.innerHTML +="Your position is not available.";break;case err.TIMEOUT:
output.innerHTML +="Request timed out while fetching your location.";break;case err.UNKNOWN_ERROR:
output.innerHTML +="Unknown error occurred while fetching your location.";break;}}</script></body></html></pre>
Geolocation Options
The getCurrentPosition() method takes the object containing the options as a third parameter.
Here is the list of options you can pass as a key to the option object.
Property
Type
Description
enableHighAccuracy
Boolean
It represents whether you want to get the most accurate location.
timeout
Number
It takes a number of milliseconds as a value for that much time you want to wait to fetch the location data.
maximumAge
Number
It takes the milliseconds as a value, specifying the maximum age of the cached location.
Example
The below code finds the most accurate location. Also, we have set milliseconds to the maximumAge, and timeout properties of the options object.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){// Options for geolocationconst options ={
enableHighAccuracy:true,
timeout:5000,
maximumAge:0};
navigator.geolocation.getCurrentPosition(getCords, errorfunc, options);}else{
output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
output.innerHTML +="The current position is: <br>";
output.innerHTML +="Latitude: "+ coords.coords.latitude +"<br>";
output.innerHTML +="Longitude: "+ coords.coords.longitude +"<br>";}functionerrorfunc(err){
output.innerHTML +="The error message is - "+ err.message +"<br>";}</script></body></html></pre>
Watching the Current Location of the User
The watchPosition() method allows you to track the live location of users. It returns the ID, which we can use with the clearWatch() method when you want to stop tracking the user.
Syntax
Follow the syntax below to use the watchPosition() method to track the live location of users.
var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)
The errorCallback and options are optional arguments.
If you want to stop tracking the user, you can follow the syntax below.
navigator.geolocation.clearWatch(id);
The clearWatch() method takes the id returned by the watchPosition() method as an argument.
Example
In the below code, we used the geolocation object's watchPosition () method to get the user's continuous position.
We used the getCords() function as a callback of the watchPosition() method, where we print the latitude and longitude of the user's position.
In the findLocation() method, we used the setTimeOut() method to stop tracking after 30 seconds.
In the output, you can observe that the code prints the user's position multiple times.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><button onclick ="findLocation()"> Find Location </button><div id ="output"></div><script>let output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){let id = navigator.geolocation.watchPosition(getCoords);setTimeout(function(){
navigator.geolocation.clearWatch(id);
output.innerHTML +="<br>Tracking stopped!";},30000);// Stop tracking after 30 seconds.}else{
output.innerHTML +="<br>Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCoords(location){let latitude = location.coords.latitude;let longitude = location.coords.longitude;
output.innerHTML +=&lt;br&gt; Latitude: ${latitude}, Longitude: ${longitude};}</script></body></html></pre>
The JavaScript Fetch API is a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a ‘GET’, ‘POST’, ‘PUT’, or ‘DELETE’ request to the server.
The window object of the browser contains the Fetch API by default.
The Fetch API provides fetch() method that can be used to access resources asynchronously across the web.
The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server.
Syntax
You can follow the syntax below to use the fetch() API in JavaScript
In the above syntax, you can handle the ‘data’ in the ‘then’ block and the error in the ‘catch’ block.
Example
In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise we handle using the ‘then’ block.
First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><div id ="output"></div><script>const output = document.getElementById('output');constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
output.innerHTML +="The data from the API is: "+"<br>";
output.innerHTML +=JSON.stringify(data);});</script></body></html></pre>
Output
The data from the API is:
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
Handling Fetch() API Response Asynchronously
You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword.
Syntax
Users can follow the syntax below to use the async/await keywords with the fetch() API.
let data =awaitfetch(URL);
data =await data.json();
In the above syntax, we used the 'await' keyword to stop the code execution until the promise gets fulfilled. After that, we again used the 'await' keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format.
Example
In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page.
<html><body><div id ="output"></div><script>asyncfunctiongetData(){let output = document.getElementById('output');letURL='https://jsonplaceholder.typicode.com/todos/6';let data =awaitfetch(URL);
data =await data.json();
output.innerHTML +="The data from the API is: "+"<br>";
output.innerHTML +=JSON.stringify(data);}getData();</script></body></html></pre>
Output
The data from the API is:
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}
Options with Fetch() API
You can also pass the object as a second parameter containing the options as a key-value pair.
Syntax
Follow the syntax below to pass the options to the Fetch() API.
Here, we have given some options to pass to the fetch() API.
method − It takes the 'GET', 'POST', 'PUT', and 'DELETE' methods as a value based on what kind of request you want to make.
body − It is used to pass the data into the string format.
mode − It takes the 'cors', 'no-cors', 'same-origin', etc. values for security reasons.
cache − It takes the '*default', 'no-cache', 'reload', etc. values.
credentials − It takes 'same-origin', 'omit', etc. values.
headers − You can pass the headers with this attribute to the request.
redirect − If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute.
Example: Making a GET Request
In the below code, we have passed the "GET" method as an option to the fetch() API.
Fetch () API fetches the data from the given API endpoint.
<html><body><div id ="output"></div><script>let output = document.getElementById("output");let options ={
method:'GET',}letURL="https://dummy.restapiexample.com/api/v1/employee/2";fetch(URL, options).then(res=> res.json()).then(res=>{
output.innerHTML +="The status of the response is - "+ res.status +"<br>";
output.innerHTML +="The message returned from the API is - "+ res.message +"<br>";
output.innerHTML +="The data returned from the API is - "+JSON.stringify(res.data);}).catch(err=>{
output.innerHTML +="The error returned from the API is - "+JSON.stringify(err);})</script></body></html></pre>
Output
The status of the response is - success
The message returned from the API is - Successfully! Record has been fetched.
The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}
Example (Making a POST Request)
In the below code, we have created the employee object containing the emp_name and emp_age properties.
Also, we have created the options object containing the method, headers, and body properties. We use the 'POST' as a value of the method and use the employee object after converting it into the string as a body value.
We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on the web page.
<html><body><div id ="output"></div><script>let output = document.getElementById("output");let employee ={"emp_name":"Sachin","emp_age":"30"}let options ={
method:'POST',// To make a post request
headers:{'Content-Type':'application/json;charset=utf-8'},
body:JSON.stringify(employee)}letURL="https://dummy.restapiexample.com/api/v1/create";fetch(URL, options).then(res=> res.json())// Getting response.then(res=>{
output.innerHTML +="The status of the request is : "+ res.status +"<br>";
output.innerHTML +="The message returned from the API is : "+ res.message +"<br>";
output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=>{
output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})</script></body></html></pre>
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been added.
The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}
Example (Making a PUT Request)
In the below code, we have created the 'animal' object.
Also, we have created the options object. In the options object, we added the 'PUT' method, headers, and animal objects as a body.
After that, we use the fetch() API to update the data at the given URL. You can see the output response that updates the data successfully.
<html><body><div id ="output"></div><script>let output = document.getElementById("output");let animal ={"name":"Lion","color":"Yellow","age":10}let options ={
method:'PUT',// To Update the record
headers:{'Content-Type':'application/json;charset=utf-8'},
body:JSON.stringify(animal)}letURL="https://dummy.restapiexample.com/api/v1/update/3";fetch(URL, options).then(res=> res.json())// Getting response.then(res=>{
console.log(res);
output.innerHTML +="The status of the request is : "+ res.status +"<br>";
output.innerHTML +="The message returned from the API is : "+ res.message +"<br>";
output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=>{
output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})</script></body></html></pre>
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}
Example (Making a DELETE Request)
In the below code, we make a 'DELETE' request to the given URL to delete the particular data using the fetch() API. It returns the response with a success message.
<html><body><div id ="output"></div><script>const output = document.getElementById("output");let options ={
method:'DELETE',// To Delete the record}letURL=" https://dummy.restapiexample.com/api/v1/delete/2";fetch(URL, options).then(res=> res.json())// After deleting data, getting response.then(res=>{
output.innerHTML +="The status of the request is : "+ res.status +"<br>";
output.innerHTML +="The message returned from the API is : "+ res.message +"<br>";
output.innerHTML +="The data added is - "+JSON.stringify(res.data);}).catch(err=>{
output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})</script></body></html></pre>
Output
The status of the request is : success
The message returned from the API is : Successfully! Record has been deleted
The data added is - "2"
Advantages of Using the Fetch() API
Here are some benefits of using the fetch() API to interact with third-party software or web servers.
Easy Syntax − It provides a straightforward syntax to make an API request to the servers.
Promise-based − It returns the promise, which you can solve asynchronously using the 'then...catch' block or 'async/await' keywords.
JSON handling − It has built-in functionality to convert the string response data into JSON data.
Options − You can pass multiple options to the request using the fetch() API.