Introduction
API stands for Application Programming Interface. It comprises a set of ready-made programs that can be integrated using JavaScript. By utilizing an API, developers can incorporate existing code to meet the requirements of their current project.
Next, let's explore a selection of beneficial and widely used APIs that are made available through HTML5.
Let's see a javascript code:
var count = 0;
function countFunction() {
count += 1;
postMessage("Welcome to our tutorial! (" + count + ")");
setTimeout("countFunction()", 1000);
}
countFunction();
HTML Geolocation API
By utilizing a geolocation API, we have the capability to retrieve the present location of the user or the visitor of the page. Additionally, the user's location can be accessed through this API only if explicit permission is granted, as this is crucial for maintaining the security and privacy of the user.
Syntax:
var loc = navigator.geolocation;
Methods available in Geolocation API:
Numerous techniques are accessible within the geolocation API. These include the following:
- The getCurrentPosition Method:
This approach allows us to retrieve the item containing characteristics like latitude, longitude, precision, and elevation.
- watchPosition Function:
By utilizing this technique, we can retrieve the user's current coordinates and receive continuous updates whenever the user's position changes or they move from one place to another.
- The clearWatch Function:
By utilizing this approach, we can cease the continuous tracking of the user by the watchPosition method.
Example 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Geolocation API</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey JTP Lover,</h1>
<h3>Welcome to our tutorial!</h3>
<button type="button" onclick="geoLoc()">
Get Location
</button>
</div>
<script>
var container = document.getElementById("container");
var pos = navigator.geolocation;
function geoLoc() {
if (pos)
pos.getCurrentPosition(getLoc);
else
container.innerHTML = "Your browser does "
+ "not support the Geolocation API.";
}
function getLoc(loc) {
container.innerHTML = "Latitude: "
+ loc.coords.latitude +
"<br>Longitude: " +
loc.coords.longitude;
}
</script>
</body>
</html>
Output:
Upon clicking the "Get Location" button, the following output is generated.
Explanation:
Within the provided code snippet, the logic has been integrated to retrieve the present latitude and longitude of the user.
HTML Drag and Drop API
This functionality is widely used in modern applications. It enables users to move an object from one location to another by dragging and dropping it.
Syntax:
By utilizing the syntax provided below, we can enable the element to be draggable, as demonstrated:
<div draggable="true">
//content of the element
</div>
Let's examine an example to gain a better understanding of this concept.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Geolocation API</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#drop {
height: 105px;
width: 105px;
border: 2px solid black;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey JTP Lover,</h1>
<h3>Welcome to our tutorial!</h3>
<p>Drag image into the container</p>
<div id="drop" ondrop="dropItem(event)"
ondragover="droppable(event)"></div>
<img src=
"https://placehold.co/400x300/34495e/ffffff?text=Logo"
alt="Example" id="image"
draggable="true" ondragstart="dragItem(event)"
height="100px" width="100px">
</div>
<script>
function droppable(e) {
e.preventDefault();
}
function dragItem(e) {
e.dataTransfer.setData("text", e.target.id);
}
function dropItem(e) {
e.preventDefault();
var content = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(content));
}
</script>
</body>
</html>
Output:
Upon moving the image, the following result can be observed:
HTML Web Storage API
By utilizing the HTML Web Storage API, it is possible to save data within the web browser. In the past, data storage was limited to cookies which could only hold a small amount of information and were unable to transmit it to the server. However, with the introduction of HTML 5, the HTML Web Storage API allows for the storage of larger quantities of data compared to cookies, enabling the transfer of this data to the server. Employing this API for data storage offers increased security as opposed to relying on cookies.
The HTML web storage API provides access to two objects, namely:
-
1.
- sessionStorage
This object allows us to store data temporarily in the web browser. This means that any data stored will be lost when the browser is refreshed or closed.
- localStorage:
By utilizing this object, we can securely store data on the browser indefinitely without an expiration date, ensuring that the information remains intact even after the browser is refreshed.
Let us understand this by taking an example.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#btnDiv {
width: 20vw;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
.btn {
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey JTP Lovers,</h1>
<h2 id="heading"></h2>
<h3 id="desc"></h3>
<div id="btnDiv">
<button class="btn" onclick="getContent()">
Get stored Data
</button>
<button class="btn" onclick="remContent()">
Remove stored Data
</button>
</div>
</div>
<script>
var head = document.getElementById('heading');
var desc = document.getElementById("desc");
function getContent() {
if (typeof (Storage) !== "undefined") {
// setItem() will set store the passed attribute
// and value in localStorage
localStorage.setItem('heading', 'Welcome to our tutorial!');
localStorage.setItem('description',
'A computer science portal for JTP Lovers.');
// This is the way of accessing the items
// stored in the storage
head.innerText = localStorage.heading;
desc.innerText = localStorage.description;
}
else {
head.innerText =
"Your browser does not support web storage API.";
}
}
function remContent() {
// removeItem() will remove the passed attribute
// and value from localStorage.
localStorage.removeItem('heading');
localStorage.removeItem('description');
head.innerText = localStorage.heading;
desc.innerText = localStorage.description;
}
</script>
</body>
</html>
Output:
Upon clicking the "get stored data" button, a message will be shown, presenting the following output.
Upon clicking the Remove Stored Data button, the message will be deleted as indicated in the following output.
HTML Web Worker API
By utilizing the Web Worker API, JavaScript uploads can be processed independently in the background, ensuring that the page remains responsive during the upload process instead of becoming unresponsive until completion. This API allows for the execution of JavaScript without impacting the overall performance of the page, enabling scripts to run autonomously.
Let us understand this by taking an example.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#btnDiv {
width: 20vw;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
.btn {
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey JTP Lovers,</h1>
<h2 id="heading"></h2>
<div id="btnDiv">
<button class="btn" onclick="getJS()">
Start executing JS
</button>
<button class="btn" onclick="remJS()">
Stop executing JS
</button>
</div>
</div>
<script>
var myWorker;
var head = document.getElementById('heading');
function getJS() {
// Below condition will check for
// the browser support.
if (typeof (Worker) !== "undefined") {
// The condition below will check for
// existence of the worker
if (typeof (myWorker) == "undefined") {
myWorker = new Worker("myScript.js");
// Above line Will create a worker that will
// execute the code of myscript.js file
}
// onmessage event triggers a function
// with the data stored in the external js file
myWorker.onmessage = function (props) {
head.innerText = props.data;
}
}
else {
head.innerText =
"Your browser does not support web storage API.";
}
}
function remJS() {
// Terminate() will terminate the current worker
myWorker.terminate();
myWorker = undefined;
}
</script>
</body>
</html>
Output:
Basic APIs in HTML5
Let's explore additional fundamental APIs provided in HTML5.
- One of these is the Ambient Light API:
This particular API enables us to retrieve data concerning the intensity of ambient light as detected by the light sensor in a device.
- Battery Status API:
Utilizing this API enables us to retrieve details regarding the device's battery status.
- Canvas 2D Context:
This API enables us to create and control graphics within a web browser.
- Clipboard API:
This API provides the capability to utilize the copy, cut, and paste features of the operating system.
- Contacts:
By utilizing this API, we can retrieve the user's address book within the web browser.
- Drag and Drop functionality:
This API enables the functionality of moving items through drag-and-drop within browser windows and across them.
- File API:
By utilizing this API, we can grant programs secure permission to interact with the device's file system.
- Categories:
By utilizing this API, we are able to grant applications the ability to interact with the additional data formats introduced in HTML5.
- Fullscreen API:
This application programming interface enables us to manage the utilization of the entire screen by users for online pages, excluding the browser's user interface.
- Gamepad API:
This API enables us to receive input support from USB gamepad controllers.
- Geolocation:
By utilizing this API, it is possible to grant web applications the ability to retrieve geographical location information pertaining to the user's device.
- getUserMedia/Stream API:
This particular API enables us to grant users access to external device information, like webcam recordings.
- Historical API:
By utilizing this API, developers can enable applications to interact with the browsing history.
- HTML Microdata:
Utilizing this API enables us to offer a method for tagging content with labels that can be understood by computers.
15.
Structured database:
By utilizing this API, we have the capability to establish a basic database system on the client side within a web browser.
- The Internationalization API:
This API enables us to grant access to locale-specific formatting and comparing strings.
- Applications without an internet connection:
By utilizing this API, developers can enable web applications to function even when offline.
- Proximity API:
Through the utilization of this API, it is possible to retrieve data regarding the proximity between a device and an object.
- Display Orientation:
This API enables developers to access the current screen orientation state, whether it is in portrait or landscape mode. It also provides functionality to detect orientation changes and fix it in a specific position.
- Choice:
Utilizing this API enables us to target elements in JavaScript by employing selectors in a CSS-like fashion.
- Server-sent events:
Utilizing this API enables the server to send data to the browser proactively, eliminating the necessity for the browser to initiate a request for it.
- User Timing API:
By utilizing this API, developers can grant access to accurate timestamps for evaluating the efficiency of applications effectively.
- Vibration API:
By utilizing this API, we can grant permission to utilize the vibration feature on the device.
- Web Audio API:
This API enables the utilization of audio processing and synthesis through API functionalities.
- Web communication:
Utilizing this API enables the facilitation of communication between browser windows from diverse origins.
- The Web Speech API:
Utilizing this API enables the provision of capabilities for receiving speech input and generating text-to-speech output.
- Web storage:
This API enables the storage of key-value pairs directly in the browser, offering a convenient solution for managing data locally.
- Web socket:
By utilizing this API, it becomes possible to establish an interactive communication session between the browser and the server.
- Web Workers:
By utilizing this API, we enable JavaScript to run scripts in the background.
- XMLHttpRequest2:
By utilizing this API, we can enhance the functionality of XMLHttpRequest by resolving issues related to same-origin policy restrictions and enabling compatibility with the latest HTML5 advancements.