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.
The worker API is a web API that allows us to run JavaScript code in the background thread. Whenever the web page loads in the browser, it becomes interactive after every <script> tag loads in the browser. Web workers allows users to interact with the web page without loading the whole JavaScript code in the browser. It increases the response time of the web page.
Create a Web Worker File
To create a web worker, you need to write a script in the external file, which you need to execute in a different file.
The filename should have a ‘.js’ extension.
In the below JavaScript code, we defined the counter() function. We used the setTimeout() method inside the function to call the counter() function after every 1000 milliseconds.
The important part of the code is the postMessage() method. It is used to send the data in the main thread.
functioncounter(){postMessage(data);// To send data to the main threadsetTimeout("counter()",1000);}counter();
Check for Web Worker Support
You should check that your browser supports the web worker or not before creating the web worker. You can use the typeof operator to check for this.
if(typeof(Worker)!=="undefined"){//"Web worker is supported by your browser!";}else{//"Web worker is not supported by your browser!";}
Create a Web Worker Object
After creating the external JavaScript file, you need to create a new Worker object by passing the path of the external JavaScript file as an argument, as shown below.
const workerObj =newWorker("testWorker.js");
To get the message main thread from the worker file, which we send using the postMessage() method, you can use the ‘onmessage’ event on the worker object, as shown below.
workerObj.onmessage=function(e){// Use the event.data};
Terminate the Execution of the Web Worker
When you start the execution of the web worker script, it continues the execution until you terminate the execution.
You can use the terminate() method to terminate the execution of the web worker as shown below.
workerObj.terminate();
Example: Complete Program of Web Worker
Filename: – index.html
In the below code, we have defined the startWorker() and stopWorker() functions to start and stop the execution of the worker.
In the startWorker() function, first, we check whether the browser supports the workers. After that, we check whether any instance of the worker is running. If not, we create a new instance of the Worker object using the script defined in the external file.
After that, we added the onmessage event on the worker object. So, whenever it gets data from the external script file, it prints it and performs other operations.
In the stopWorker() function, we use the terminate() method with the workerObj object to terminate the execution of the worker.
workerObj =newWorker("app.js");
workerObj.onmessage=function(event){//Getting the message from web worker
output.innerHTML +="Event data is: "+ event.data +"<br>";};}}else{
output.innerHTML +="Web worker is not supported by your browser.";}}functionstopWorker(){// To stop the web worker.if(typeof workerObj !=="undefined"){
workerObj.terminate();
workerObj =undefined;}}</script></body></html></pre>
Filename: - app.js
In the below code, we have defined the counter() function. In the counter() function, we used the setTimeOut() method to call the counter() function after every second. It also posts the data into the main thread using the postMessage() method.
var i =0;functiontimedCount(){
i = i +1;postMessage(i);setTimeout("timedCount()",500);}timedCount();
Output
To run the above code, you need to make sure that the index.html and app.js file is on the live web server. You can also use the localhost. Also, make sure to add the correct path for the app.js file in the Worker object inside the index.html file.
You can also use multiple workers in the same file to run multiple scripts in the background.
Web Worker Use Cases
The above example is simple, and in such cases, you dont need to use web workers, but it is only for demonstrations.
Here are the real-time use cases of the web workers.
When you need to execute large or complex mathematical script
In the HTML games, you may use web workers
If you want to improve the website performance
In parallel downloads, when you need to execute multiple threads
For the background data synchronization
In the machine learning
For generating reports
To process audio and videos
Web Workers and the DOM
As you need to define the scripts for the web workers in the external file, you can't use the below objects in the external file.
The window object
The document object
The parent object
However, you can use the below objects in the web workers.
JavaScript Forms API is a web API that allows us to interact with and manipulate HTML forms. It provides a set of methods and properties that are used to perform client-side form validation. Its also helpful to ensure data integrity before form submission. The forms API also referred to as Form Validation API or Constraint Validation API.
Here, we will discuss how to use various methods and properties to validate the form data using JavaScript.
Constraint Validation DOM Methods
In JavaScript, the constraint validation DOM method validates the input value by referencing the input fields. It validates the input value based on the HTML attributes you have used with the input.
After validating the input value, it returns a boolean value, representing whether the input value is valid.
Here is the list of the constraint validation methods.
Method
Description
checkValidity()
It returns a boolean value based on whether the input element contains a valid value.
setCustomValidity()
It is used to set the custom message to the validationMessage property.
Syntax
We can follow the syntax below to use the form validation methods.
In the above syntax, you need to access the element using the selector and take it as a reference of the checkValidity() or setCustomValidity() method. The setCustomValidity() method takes the string message as an argument.
Example: Using the checkValidity() method
We created the number input in the code below and set 10 to the min attribute.
In the validateInput() function, we access the number input using the id and use the checkValidity() to validate the value of the number input.
If checkValidity() method returns false, we print the validation message. Otherwise, we print the numeric value.
<html><body><input type ="number" min ="10" id ="num" required><p id ="output"></p><button onclick ="validateInput()"> Validate Number </button><script>const output = document.getElementById("output");functionvalidateInput(){let num = document.getElementById("num");if(num.checkValidity()==false){
output.innerHTML ="Please enter a number greater than 10";}else{
output.innerHTML ="Your number is "+ num.value;}}</script></body></html></pre>
Example: Using the setCustomValidity() Method
In the below code, we have defined the number input to take the users age in the input.
In the validateAge() function, we access the age input using its id and perform the custom validation on the input value. Based on the validation, we use the setCustomValidity() to set the custom validation message.
At last, we use the reportValidity() method to show the validation message set using the setCustomValidity() method.
You can enter the age below 18, and observe the validation message.
<html><body><form><label> Enter your age:</label><input type ="number" id ="age" required><br><br><button type ="button" onclick ="validateAge()"> Validate Age </button></form><div id ="message"></div><script>functionvalidateAge(){const ageInp = document.getElementById("age");const output = document.getElementById("message");const age =parseInt(ageInp.value);if(isNaN(age)){
ageInp.setCustomValidity("Please enter a valid number.");}elseif(age <18){
ageInp.setCustomValidity("You must be at least 18 years old.");}else{
ageInp.setCustomValidity("");// To remove custom error message
output.innerHTML ="Age is valid!";}
ageInp.reportValidity();// To display custom validation message}</script></body></html></pre>
Constraint Validation DOM Properties
JavaScript also contains the DOM properties for constraint validation. It is used to check the particular validation of the input value.
Here, we have listed all DOM properties that can be used for the constraint validation.
Property
Description
validity
It contains multiple properties to perform the particular validation on the input element.
validationMessage
It contains the validation message when the input element doesn't contain valid data.
willValidate
It represents whether the input data will be validated.
Properties of the 'validity' Property
In JavaScript, each element has the 'validity' property, containing multiple properties. You can use the particular property of the 'validation' property to perform the validation.
Here, we have listed all properties of the 'validity' property.
Property
Description
customError
It contains a true boolean value when you set the custom validity message.
patternMismatch
When the parent element's value doesn't match the pattern, it sets true.
rangeOverflow
It returns a boolean value based on whether the input value is greater than the max attribute's value.
rangeUnderflow
It returns a boolean value based on whether the input value is less than the min attribute's value.
stepMismatch
It returns a boolean value based on whether the step is mismatching in the numeric input.
tooLong
If the length of the input element's value is greater than the maxLength attribute's value, it returns true. Otherwise, it returns false.
typeMismatch
When the type of entered value doesn't match the 'type' attribute's value, it returns true.
valueMissing
It returns a boolean value based on whether the input element is empty.
valid
It returns true when the input element is valid.
Syntax
Users can follow the syntax below to use the properties of the validation property.
element.validity.property;
You can use the different properties of the validity property of the element to validate the input elements value.
Example
In the below code, we have defined the number input and set 300 for the value of the max attribute.
In the validateNumber() function, we use the rangeOverflow property of the validity property of the input element to check whether the input value is greater than 300.
If the rangeOverflow property returns true, we print the Number is too large. Otherwise, we print the numeric value.
<html><body><form><label> Enter Any Number:</label><input type ="number" id ="num" max ="300" required><br><br><button type ="button" onclick ="validateNumber()"> Validate Number </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateNumber(){const numInput = document.getElementById('num');if(numInput.validity.rangeOverflow){
output.innerHTML ="Number is too large";}else{
output.innerHTML ="Number is valid";}}</script></body></html></pre>
Example
In the below code, we have defined the text input.
In the validateText() function, we access the string input. After that, we used the valueMissing property of the validity property to check whether the input value is empty.
In the output, you can keep the input value empty, click the validate text button and observe the error message.
<html><body><form><label> Enter any text:</label><input type ="text" id ="str" required><br><br><button type ="button" onclick ="validateText()"> Validate Text </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateText(){const strInput = document.getElementById('str');if(strInput.validity.valueMissing){
output.innerHTML ="Please enter a value.";}else{
output.innerHTML ="You have entered "+ strInput.value +".";}}</script></body></html></pre>
You can also use the other properties of the validity property to validate the form input data. If the data is not valid, you can show the custom error message using the setCustomValidity() method.