HTML - module 8 - API

revision:


Content

API stands for "Application Programming Interface". DOM (document object model) API geolocation API drag and drope API web storage API web workers API canvas API fetch API history API


API stands for "Application Programming Interface".

top

An application can be any software that performs a specific task and the interface is a point where two applications communicate. One application acts as a client and the other acts as a server. A client asks for some resource, say for example a photo, and the server sends that photo to the client.

The client here can be your mobile phone, desktop or laptop computer, or any device you use to surf the internet. And the server is a bigger computer that stores the data you want.

HTML provides several APIs (Application Programming Interfaces) that allow developers to interact with and manipulate web pages dynamically. These APIs are typically accessed through JavaScript, which works alongside HTML to create interactive and dynamic web applications.

There are four main types of APIs:

Open APIs : also known as Public APIs, there are no restrictions to access these types of APIs because they are publicly available.

Partner APIs: one needs specific rights or licenses in order to access this type of APIs because they are not available to the public.

Internal APIs : also known as Private APIs, only internal systems expose this type of API, which is, therefore, less known and often meant to be used inside the company. The company uses this type of API among the different internal teams to be able to improve its products and services.

Composite APIs : this type of API combines different data and service APIs. It is a sequence of tasks that run synchronously as a result of the execution and not at the request of a task. Its main uses are to speed up the process of execution and improve the performance of the listeners in the web interfaces.


DOM (document object model) API

top

The DOM API is one of the most fundamental APIs in web development. It represents the structure of an HTML document as a tree of objects, allowing developers to manipulate the content, structure, and style of a web page dynamically.

Key features

Access and modify HTML elements (document.getElementById, document.querySelector, etc.).
Add or remove elements and attributes.
Respond to user interactions (e.g., clicks, input changes).
Dynamically update styles and content.

Examples

        <script>
            // Select an element by its ID
            const heading = document.getElementById('heading');
            // Change the text content
            heading.textContent = 'Hello, World!';
            // Add a CSS class
            heading.classList.add('highlight');
        </script>
    

geolocation API

top

is used to get the geographical position of a user

Since this can compromise privacy, the position is not available unless the user approves it.
Note: geolocation is most accurate for devices with GPS, like smartphones.

The getCurrentPosition() method is used to return the user's position.

example: getCurrentPostion() method()

Click the button to get your coordinates.

code:
                    <div>
                        <button style="margin-left: 3vw" onclick="getLocation()">Try It</button>
                        <p class="examples" id="demo"></p>
                    </div>
                    <script>
                        var x = document.getElementById("demo");
                        function getLocation() {
                            if (navigator.geolocation) {
                                navigator.geolocation.getCurrentPosition(showPosition);
                            } else { 
                                x.innerHTML = "Geolocation is not supported by this browser.";
                            }
                        }
                        function showPosition(position) {
                            x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
                        }
                    </script> 
                

Handling errors and rejections: the second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

example: getCurrentPostion() method() - handling errors

click the button to get your coordinates.

code:
                    <div>
                        <button style="margin-left: 3vw" onclick="getLocation1()">Try It</button>
                        <p class="examples" id="demo1"></p>
                    </div>
                    <script>
                        var xx = document.getElementById("demo1");
                        function getLocation1() {
                            if (navigator.geolocation) {
                                navigator.geolocation.getCurrentPosition(showPosition1, showError);
                                } else { 
                                    xx.innerHTML = "Geolocation is not supported by this browser.";
                                }
                            }
                        function showPosition1(position) {
                            xx.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
                        }
                        function showError(error) {
                            switch(error.code) {
                                case error.PERMISSION_DENIED:
                                xx.innerHTML = "User denied the request for Geolocation."
                                break;
                                case error.POSITION_UNAVAILABLE:
                                xx.innerHTML = "Location information is unavailable."
                                break;
                                case error.TIMEOUT:
                                xx.innerHTML = "The request to get user location timed out."
                                break;
                                case error.UNKNOWN_ERROR:
                                xx.innerHTML = "An unknown error occurred."
                                break;
                                }
                            }
                    </script>
                

To Display the result in a map, you need access to a map service, like Google Maps.

The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available.

The geolocation object also has other interesting methods: 1/ watchPosition() - returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car); 2/clearWatch() - stops the watchPosition() method.


drag and drop API

top

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

example: drag and drop

Drag the W3Schools image into the rectangle:


logo
code:
                    <div>
                        <p class="examples">Drag the W3Schools image into the rectangle:</p>
                        <div style="margin-left: 3vw"; id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
                        <br>
                        <img id="drag1" src="../../../pics/img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
                    </div>
                    <script>
                        function allowDrop(ev) {
                        ev.preventDefault();
                        }
                        
                        function drag(ev) {
                        ev.dataTransfer.setData("text", ev.target.id);
                        }
                        
                        function drop(ev) {
                        ev.preventDefault();
                        var data = ev.dataTransfer.getData("text");
                        ev.target.appendChild(document.getElementById(data));
                        }
                    </script>
                

To make an element draggable, set the draggable attribute to true: <img draggable="true">. Then, specify what should happen when the element is dragged. In the example above, the "ondragstart" attribute calls a function, drag(event), that specifies what data to be dragged. The dataTransfer.setData() method sets the data type and the value of the dragged data:

code:       
            function drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
        }

In this case, the data type is "text" and the value is the id of the draggable element ("drag1").

The ondragover event specifies where the dragged data can be dropped. By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element. This is done by calling the event.preventDefault() method for the ondragover event: event.preventDefault()

When the dragged data is dropped, a drop event occurs.In the example above, the ondrop attribute calls a function, drop(event):

        function drop(ev) {
          ev.preventDefault();
          var data = ev.dataTransfer.getData("text");
          ev.target.appendChild(document.getElementById(data));
        }
    

web storage API

top

With web storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML web storage objects:HTML web storage provides two objects for storing data on the client:1/ window.localStorage - stores data with no expiration date, 2/ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed). Before using web storage, check browser support for localStorage and sessionStorage:

The localStorage objectThe localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

The sessionStorage object:The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.


web workers API

top

What is a web worker?:when executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Examples

        <script>
            // Store data in localStorage
            localStorage.setItem('username', 'JohnDoe');

            // Retrieve data
            const username = localStorage.getItem('username');
            console.log(username); // Output: JohnDoe
        </script>
    

canvas API

top

The canvas API provides a way to draw graphics, animations, and visualizations on a web page using JavaScript. It is commonly used for games, data visualizations, and image editing tools.

Key features

Draw shapes, lines, and text.
Render images and apply transformations.
Create animations and interactive graphics.

Examples

    <canvas id="myCanvas" width="200" height="200"></canvas>
    <script>
      const canvas = document.getElementById('myCanvas');
      const ctx = canvas.getContext('2d');
      
      // Draw a rectangle
      ctx.fillStyle = 'blue';
      ctx.fillRect(50, 50, 100, 100);
    </script>

fetch API

top

The Fetch API is used to make network requests to retrieve resources from a server. It is a modern replacement for XMLHttpRequest and provides a simpler, promise-based syntax.

Key features

Fetch data from APIs or external resources.
Handle responses in various formats (JSON, text, blobs, etc.).
Perform asynchronous operations.

Examples

    <script>
        fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    </script>

history API

top

The History API enables developers to manipulate the browser's session history. It is commonly used in single-page applications (SPAs) to update the URL without reloading the page.

Key features

Push new states onto the history stack (history.pushState).
Replace the current state (history.replaceState).
Listen for navigation events (popstate event).

Examples

    <script>
        // Update the URL without reloading the page
        history.pushState({ page: 'home' }, 'Home', '/home');

        // Listen for back/forward navigation
        window.addEventListener('popstate', event => {
        console.log('Navigated to:', event.state);
    </script>