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>
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>
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>
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>
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.
<html><body><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
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>
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>
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 +=`<br> Latitude: ${latitude}, Longitude: ${longitude}`;}</script></body></html>
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>
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>
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>
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>
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>
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>
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.
<html><body><button onclick ="startWorker()"> Start Counter </button><button onclick ="stopWorker()"> Stop Counter </button><div id ="output"></div><script>let output = document.getElementById('output');let workerObj;functionstartWorker(){if(typeof(Worker)!=="undefined"){if(typeof workerObj ==="undefined"){
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>
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>
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>
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>
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>
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.
The web storage API in JavaScript allows us to store the data in the user’s local system or hard disk. Before the storage API was introduced in JavaScript, cookies were used to store the data in the user’s browser.
The main problem with the cookies is that whenever browsers request the data, the server must send it and store it in the browser. Sometimes, it can also happen that attackers can attack and steal the data.
In the case of the storage API, we can store the user’s data in the browsers, which remains limited to the user’s device.
JavaScript contains two different objects to store the data in the local.
localStorage
sessionStorage
Here, we have explained the local and session storage.
The Window localStorage Object
The localStorage object allows you to store the data locally in the key-value pair format in the user’s browser.
You can store a maximum of 5 MB data in the local storage.
Whatever data you store into the local storage, it never expires. However, you can use the removeItem() method to remove the particular or clear() to remove all items from the local storage.
Syntax
We can follow the syntax below to set and get items from the browser’s local storage.
localStorage.setItem(key, value);// To set key-value pair
localStorage.getItem(key);// To get data using a key
In the above syntax, the setItem() method sets the item in the local storage, and the getItem() method is used to get the item from the local storage using its key.
Parameters
key − It can be any string.
value − It is a value in the string format.
Example
In the below code, we set the ‘fruit’ as a key and ‘Apple’ as a value in the local storage inside the setItem() function. We invoke the setItem() function when users click the button.
In the getItem() function, we get the value of the ‘fruit’ key from the local storage.
Users can click the set item button first and then get the item to get the key-value pair from the local storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){
localStorage.setItem("fruit","Apple");}functiongetItem(){const fruitName = localStorage.getItem("fruit");
output.innerHTML ="The name of the fruit is: "+ fruitName;}</script></body></html>
The localStorage doesn’t allow you to store the objects, functions, etc. So, you can use the JSON.stringify() method to convert the object into a string and store it in the local storage.
Example: Storing the object in the local storage
In the below code, we have created the animal object. After that, we used the JSON.stringify() method to convert it into the string and store it as a value of the ‘animal’ object.
Users can click the set item button to set the object into the local storage and get the item button to get the key-value pair from the local storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){const animal ={
name:"Lion",
color:"Yellow",
food:"Non-vegetarian",}
localStorage.setItem("animal",JSON.stringify(animal));}functiongetItem(){const animal = localStorage.getItem("animal");
output.innerHTML ="The animal object is: "+ animal;}</script></body></html>
Example: Removing the items from the local storage
In the below code, we set the ‘name’ and ‘john’ key-value pair in the local storage when the web page loads into the browser.
After that, users can click the get item button to get the item from local storage. It will show you the name.
You can click the get item button again after clicking the remove item button, and it will show you null as the item got deleted from the local storage.
<html><body><button onclick ="getItem()"> Get Item </button><button onclick ="removeItem()"> Remvoe Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');
localStorage.setItem('name','John');functiongetItem(){
output.innerHTML ="The name of the person is: "+
localStorage.getItem('name');}functionremoveItem(){
localStorage.removeItem('name');
output.innerHTML ='Name removed from local storage. Now, you can\'t get it.';}</script></body></html>
The Window sessionStorage Object
The sessionStorage object also allows storing the data in the browser in the key-value pair format.
It also allows you to store the data up to 5 MB.
The data stored in the session storage expires when you close the tab of the browsers. This is the main difference between the session storage and local storage. You can also use the removeItem() or clear() method to remove the items from the session storage without closing the browser’s tab.
Note Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser’s tab after closing it. If you close the browser window, it will definitely delete the session storage data.
Syntax
Follow the syntax below to use the session storage object to set and get data from the session storage.
sessionStorage.setItem(key, value);// To set key-value pair
sessionStorage.getItem(key);// To get data using a key
The setItem() and getItem() methods give the same result with the sessionStorage object as the localStorage object.
Parameters
key − It is a key in the string format.
value − It is a value for the key in the string format.
Example
In the below code, we used the ‘username’ as a key and ‘tutorialspoint’ as a value. We store the key-value pair in the sessionStorage object using the setItem() method.
You can click the get item button after clicking the set item button to get the key-value pair from the session storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="output"></p><script>const output = document.getElementById('output');functionsetItem(){
sessionStorage.setItem("username","tutorialspoint");}functiongetItem(){const username = sessionStorage.getItem("username");
output.innerHTML ="The user name is: "+ username;}</script></body></html>
You can’t store the file or image data directly in the local or session storage, but you can read the file data, convert it into the string, and store it in the session storage.
Example
In the below code, we have used the <input> element to take the image input from users. When a user uploads the image, it will call the handleImageUpload() function.
In the handleImageUpload() function, we get the uploaded image. After that, we read the image data using the FileReader and set the data into the session storage.
In the getImage() function, we get the image from the session storage and set its data as a value of the ‘src’ attribute of the image.
Users can upload the image first and click the get Image button to display the image on the web page.
<html><body><h2> Upload image of size less than 5MB</h2><input type ="file" id ="image" accept ="image/*" onchange ="handleImageUpload()"><div id ="output"></div><br><button onclick ="getImage()"> Get Image </button><script>// To handle image uploadfunctionhandleImageUpload(){const image = document.getElementById('image');const output = document.getElementById('output');const file = image.files[0];// Read Image fileif(file){const reader =newFileReader();
reader.onload=function(event){const data = event.target.result;// Storing the image data in sessionStorage
sessionStorage.setItem('image', data);};
reader.readAsDataURL(file);}}// Function to get imagefunctiongetImage(){let data = sessionStorage.getItem("image");
output.innerHTML =`<img src="${data}" alt="Uploaded Image" width="300">`;}</script></body></html>
You can also use the removeItem() or clear() method with the sessionStorage object like the localStorage.
Cookie Vs localStorage Vs sessionStorage
Here, we have given the difference between the cookie, localStorage, and sessionStorage objects.
Feature
Cookie
Local storage
Session storage
Storage Limit
4 KB per cookie
5 MB
5 MB
Expiry
It has an expiry date.
It never expires.
It gets deleted when you close the browser window.
Accessibility
It can be accessed on both the client and server.
It can be accessed by the client only.
It can be accessed by the client only.
Security
It can be vulnerable.
It is fully secured.
It is fully secured.
Storage Object Properties and Methods
Property/Method
Description
key(n)
To get the name of the nth key from the local or session storage.
length
To get the count of key-value pairs in the local or session storage.
getItem(key)
To get a value related to the key passed as an argument.
setItem(key, value)
To set or update key-value pair in the local or session storage.
removeItem(key)
To remove key-value pairs from the storage using its key.
clear()
To remove all key-value pairs from the local or session storage.
In JavaScript, the history API allows us to access the browsers history. It can be used to navigate through the history.
JavaScript History API provides us with methods to manipulate window history object. History object is a property of JavaScript window object. The window history object contains the array of visited URLs in the current session
The history API is very powerful tool to create may useful effects. For example, we can use it to implement history based undo redo system.
How to use JavaScript History API?
The History API is a very simple API to use. There are just a few methods and a property that you need to know about:
back() − This method navigates back to the previous page in the history.
forward() − This method navigates forward to the next page in the history.
go() − This method navigates to a specific page in the history. The number that you pass to the go() method is the relative position of the page that you want to navigate to. For example, to navigate to the previous page in the history, you would pass -1 to the go() method.
length − This property returns the length of the history list. It tells us the number of pages that have been visited by the user.
Syntax
Followings are the syntaxes to use the different methods and property of the history object −
// Load the previous URL in the history list
history.back();// Load the next URL in the history list
history.forward();// Load the page through its number
history.go(-2);// This will go to the previous 2nd page
history.go(2);// This will go to the next 2nd page// Get the length of the history listconst length = history.length;
Loading Previous Page in History List
The JavaScript history back() method of the history object loads the previous URL in the history list. We can also use the history go() method to load the previous page. The difference between these two methods is that back() method only load the immediate previous URL in history list but we can use the go() method to load any previous URL in the history list.
Example: Using back() method to load previous page
In the example below, we have used history back() method to load the previous page the user has already visited.
Please note that if you have no previous page in the history list (i.e., you have not visited any page previously), the back() method will not work.
We have implemented a back button, on clicking that we can load the previous visited page.
<html><body><p> Click "Load Previous Page" button to load previous visited page </p><button onclick="goback()"> Load Previous Page </button><p id ="output"></p><script>functiongoback(){
history.back();
document.getElementById("output").innerHTML +="You will have gone to previous visited page if it exists";}</script></body></html>
Example: Using go() method to load the previous page
In the example bellow, we have used the history go() method to load to the 2nd previous visited page from the current web page.
<html><body><p> Click the below button to load 2nd previous visited page</p><button onclick ="moveTo()"> Load 2nd Previous Page </button><p id ="output"></p><script>functionmoveTo(){
history.go(-2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous visited page if it exists.";}</script></body></html>
Loading Next Page in History List
The JavaScript history forward() method of the history object loads the next URL in the history list. We can also use the history go() method to load the next page. The difference between these two methods is that forward() method only loads the immediate next URL in history list but we can use the go() method to load any next URL in the history list.
Example: Using forward() method to load next page
In the below code, click the button to go to the next URL. It works as the forward button of the browser.
<html><body><p> Click "Load Next Page" button to load next visited page</p><button onclick ="goForward()"> Load Next Page </button><p id ="output"></p><script>functiongoForward(){
history.forward();
document.getElementById("output").innerHTML ="You will have forwarded to next visited page if it exists."}</script></body></html>
Example: Using go() method to load next page
In the example below, we have used the go() method to move to the 2nd previous page from the current web page.
<html><body><p> Click the below button to load next 2nd visited page</p><button onclick ="moveTo()"> Load 2nd Next Page </button><p id ="output"></p><script>functionmoveTo(){
history.go(2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd next visited page if it exists.";}</script></body></html>
Get the length of the history list
We can use the history.length proerty to get the length of history list.
Example
Try the follwing example −
<html><body><p> Click the below button to get the lenght of history list</p><button onclick ="moveTo()"> Get Lenght of History List </button><p id ="output"></p><script>const output = document.getElementById("output");functionmoveTo(){
output.innerHTML = history.length;}</script></body></html>
A Web API is an application programming interface (API) for web. The concept of the Web API is not limited to JavaScript only. It can be used with any programming language. Lets learn what web API is first.
What is Web API?
The API is an acronym for the Application Programming Interface. It is a standard protocol or set of rules to communicate between two software components or systems.
A web API is an application programming interface for web.
The API provides an easy syntax to use the complex code. For example, you can use the GeoLocation API to get the coordinates of the users with two lines of code. You dont need to worry about how it works in the backend.
Another real-time example you can take is of a power system at your home. When you plug the cable into the socket, you get electricity. You dont need to worry about how electricity comes into the socket.
There are different types of web APIs, some are as follow −
Browser API (Client-Side JavaScript API)
Server API
Third Party APIs
Lets discuss each of the above type of web APIs in detail −
Browser API (Client-side JavaScript API)
The browser APIs are set of Web APIs that are provided by the browsers.
The browser API is developed on top of the core JavaScript, which you can use to manipulate the web page’s functionality.
There are multiple browser APIs available which can be used to interact with the web page.
Following is a list of common browser APIs −
Storage API − It allows you to store the data in the browser’s local storage.
DOM API − It allows you to access DOM elements and manipulate them.
History API − It allows you to get the browsers history.
Fetch API − It allows you to fetch data from web servers.
Forms API − It allows you to validate the form data.
Server API
A server API provides different functionalities to the web server. Server APIs allow developers to interact with server and access data and resources.
For example, REST API is a server API that allows us to create and consume the resources on the server. A JSON API is popular API for accessing data in JSON format. The XML API is a popular API for accessing data in XML format.
Third-party APIs
The third-party API allows you to get the data from their web servers. For example, YouTube API allows you to get the data from YouTubes web server.
Here is the list of common third-party APIs.
YouTube API − It allows you to get YouTube videos and display them on the website.
Facebook API − It allows you to get Facebook posts and display them on the website.
Telegram API − It allows you to fetch and send messages to the telegram.
Twitter API − It allows you to get tweets from Twitter.
Pinterest API − It allows you to get Pinterest posts.
You can also create and expose API endpoints for your own software. So, other applications can use your API endpoints to get the data from your web server.
Fetch API: An Example of Web API
Here is an example of how to use the fetch API. In the below example, we Fetch API to access data from a given URL (‘https://jsonplaceholder.typicode.com/todos/5). The fetch() method returns a promise that 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><h3> Fetch API: An Example of Web API</h3><div id ="output"></div><script>constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
document.getElementById('output').innerHTML +="The data accessed from the API: "+"<br>"+JSON.stringify(data);});</script></body></html>
JavaScript Web API List
Here, we have listed the most common web APIs.
API
Description
Console API
It is used to interact with the browsers console.
Fetch API
It is used to fetch data from web servers.
FullScreen API
It contains various methods to handle HTML elements in full-screen mode.
GeoLocation API
It contains the methods to get the users current location.
History API
It is used to navigate in the browser based on the browsers history.
MediaQueryList API
It contains methods to query media.
Storage API
It is used to access the local and session storage.
Forms API
It is used to validate the form data.
In upcoming chapters, we will cover the above APIs in details/>
In JavaScript, the ‘console’ object is a property of the window object. It allows the developers to access the debugging console of the browser.
The console object contains the various methods used for different functionalities. In Node.js, the console object is used to interact with the terminal.
We access the console object using the window object or without using the window object – window.console or just console.
Console Object Methods
There are many methods available on the console object. These methods are used to perform a number of task such testing, debugging and logging.
You may access the ‘console’ object methods using the following syntax −
You can observe outputs in the console. To open the console, use the Ctrl + shift + I or Cmd + shift + I key.
Below, we will cover some methods of the console object with examples.
JavaScript console.log() Method
You can use the console.log() method to print the message in the debugging console. It takes the expression or text message as an argument.
Syntax
Follow the syntax below to use the console.log() method.
console.log(expression);
In the above syntax, the expression can be a variable, mathematical expression, string, etc., which you need to print in the console.
Example
In the below code, clicking the button will invoke the ‘printMessage’ function. The function prints the string text and number value in the console.
<html><body><h2> JavaScript console.log() Method </h2><button onclick ="printMessage()"> Print Message in Console </button><p> Please open the console before you click "Print Message in Console" button</p><script>functionprintMessage(){
console.log("You have printed message in console!");let num =10;
console.log(num);}</script></body></html>
JavaScript console.error() Method
The console.error() method prints the error message in the console, highlighting the error with a red background.
Syntax
Follow the syntax below to use the console.error() method.
console.error(message);
The console.error() message takes a message as an argument.
Example
In the below code, printError() function logs the error in the console when you click the button. You can observe the error highlighted with the red background.
<html><body><h2> JavaScript console.error() Method </h2><button onclick="printError()"> Print Error Message in Console </button><p> Please open the console before you click " Print Error Message in Console" button.</p><script>functionprintError(){
console.error("Error occured in the code!");}</script></body></html>
JavaScript console.clear() Method
The console.clear() method clears the console.
Syntax
Follow the syntax below to use the console.clear() method.
console.clear()
Example
In the below code, we print messages to the console. After that, when you click the button, it executes the clearConsole() function and clears the console using the console.clear() method.
<html><body><h2> JavaScript console.clear() Method </h2><button onclick ="clearConsole()"> Clear Console </button><p> Please open the console before you click "Clear Console" button</p><script>
console.log("Hello world!");
console.log("Click the button to clear the console.");functionclearConsole(){
console.clear();}</script></body></html>
The console object methods list
Here, we have listed all methods of the console object.
Method
Method Description
assert()
It prints the error message in the console if the assertion passed as a parameter is false.
clear()
It clears the console.
count()
It is used to count how many times the count() method is invoked at a specific location.
error()
It displays the error message in the console.
group()
It is used to create a group of messages in the console.
groupCollapsed()
It is used to create a new collapsed group of messages in the console.
groupEnd()
It is used to end the group.
info()
It shows the informational or important message in the console.
log()
It prints the message into the output.
table()
It shows the data in the tabular format in the console.
The location object in JavaScript provides information about the browser’s location, i.e., URLs. It is a built-in property of both the window and document objects. We can access it using either window.location or document.location.
The ‘location’ object contains various properties and methods to get and manipulate the information of the browser’s location (URL).
JavaScript Location Object Properties
We can use the properties of the location object to get information of URL:
hash − This property is used to set or get the anchor part of the URL.
host − This property is used to set or get the hostname or port number of the URL.
hostname − This property is used to set the hostname.
href − This property is used to set or get the URL of the current window.
origin − This property returns the protocol, domain, and port of the URL.
pathname − This property updates or gets the path name.
port − This property updates or gets the port of the URL.
protocol − This property updates or gets the protocol.
search − This property is used to set or get the query string of the URL.
Syntax
Follow the syntax below to access the location object’s properties and methods −
window.location.property;
OR
location.property;
You may use the ‘window’ object to access the ‘location’ object.
Here, we have demonstrated the use of some properties of the location object with examples.
Example: Accessing location host property
The location.host property returns the host from the current URL. However, you can also change the host using it.
In the below code, we extract the host from the URL. You can see that it returns ‘www.tutorialspoint.com’.
<html><body><div id="output"></div><script>const host = location.host;
document.getElementById("output").innerHTML ="The host of the current location is: "+ host;</script></body></html>
Output
The host of the current location is: www.tutorialspoint.com
Example: Accessing location protocol property
The location.protocol propery is used to get used in the current URL. You can also use it to update the protocol.
Try the following example to use the location.protocol property –
<html><body><div id ="output"></div><script>
document.getElementById("output").innerHTML ="The protocol of the current location is: "+ location.protocol;</script></body></html>
Output
The protocol of the current location is: https:
Example: Accessing location hostname property
The location.hostname property returns the host name of the current URL. You can use it to the hostname as well.
Try the following example to use location.hostname property
<html><body><div id ="output"></div><script>
document.getElementById("output").innerHTML ="The host name of the current location is: "+ location.hostname;</script></body></html>
Output
The host name of the current location is: www.tutorialspoint.com
Example: Accessing location pathname property
The location.pathname property returns the path name of the current location. You can set the path name using it.
<html><body><div id ="output"></div><script>
document.getElementById("output").innerHTML ="The protocol of the current location is: "+ location.pathname;</script></body></html>
Output
The protocol of the current location is: /javascript/javascript_location_object.htm
JavaScript Location Object Methods
We can also use the methods of the location object to navigation to new URLs −
assign(url) − This method loads a new document at the specified URL.
replace(url) − This method replaces the current document with a new document at the specified URL.
reload() − This method reloads the current document.
JavaScript location assign() method
The location.assign() method takes the URL and changes the URL in the current window. In short, it opens a new web page.
Syntax
Follow the syntax below to use the location.assign() method in JavaScript −
location.assign();
Example
In the below code, when you click the ‘Go to home page’ button, it will redirect you to the home page of the tutorialpoint website.
<html><body><div id="output"></div><button onclick="changePage()">Go to Home Page</button><script>let output = document.getElementById("output");functionchangePage(){
window.location.assign("https://www.tutorialspoint.com/");}</script></body></html>
Location Object Properties List
Here, we have listed all properties of the Location object.
Property
Description
hash
It is used to set or get the anchor part of the URL.
host
It is used to set or get the hostname or port number of the URL.
hostname
It is used to set the hostname.
href
It is used to set or get the URL of the current window.
origin
It returns the protocol, domain, and port of the URL.
pathname
To update or get the path name.
port
To update or get the port of the URL.
protocol
To update or get the protocol.
search
To set or get the query string of the URL.
Location Object Methods List
Here, we have listed all methods of the Location object.
Method
Description
assign()
To load resources at a particular URL.
reload()
To reload the web page.
replace()
To replace the resources of the current webpage with another webpage’s resources.