HTML APIs in Depth
Tags: webdev, html, beginners, javascript
Published: 2020-08-17 20:40:37

*HTML5 has a set of APIs that provide a scripting interface for some of the features of the language.*


#### Are you a person who just started with HTML/CSS or someone who wants to have an in-depth knowledge of the advanced features of HTML? Then you are in the right place. So grab a cup of coffee and enjoy the first part of our HTML series, HTML APIs in Depth.

A few days before, I came across an [article](https://www.smashingmagazine.com/2017/02/designing-html-apis/) by Lea Verou, where she wrote about the design of HTML APIs and how we might write better documentation for web designers. There she pointed out a crucial aspect of our perception. She says:

> _As JavaScript developers, we often forget that not everyone has the same knowledge as us. It’s called the curse of knowledge._

When beginners of HTML/CSS struggle to write code in JavaScript, that’s where HTML5 APIs come to their rescue. HTML APIs are a collection of JS libraries which can be used directly in HTML files without incorporating any customize JavaScript code

So in addition to specifying markup, HTML5 specifies scripting [application programming interfaces](https://en.wikipedia.org/wiki/Application_programming_interfaces) (APIs) that can be used along with [JavaScript](https://en.wikipedia.org/wiki/JavaScript).

This technique helps us perform tasks in the web browser and supported mobile devices that were not possible in previous versions of HTML.

Why HTML APIs
-------------

Now, many advanced JavaScript might question the need for such APIs. But these APIs not only benefit people with limited JavaScript skills but also help programmers save time by using simple APIs for tedious tasks. It makes the process more flexible for programming

What is API?
------------

According to Wikipedia:

> “An application programming interface (**API**) is a computing interface which defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc.”

In a typical HTML API, the calls and requests along with definitions and protocols are written and invoked with HTML itself. HTML API uses certain class or attribute patterns used in the HTML element to invoke the functions in the API.

Lists of HTML APIs
------------------

*   The [canvas element](https://en.wikipedia.org/wiki/Canvas_element) for [immediate mode](https://en.wikipedia.org/wiki/Immediate_mode) 2D drawing.
*   Timed media playback
*   Offline Web Applications
*   Document editing
*   [Drag-and-drop](https://en.wikipedia.org/wiki/Drag-and-drop)
*   [Cross-document messaging](https://en.wikipedia.org/wiki/Cross-document_messaging)
*   Browser history management
*   [MIME-type](https://en.wikipedia.org/wiki/MIME_type) and protocol handler registration
*   [Microdata](https://en.wikipedia.org/wiki/Microdata_(HTML))
*   [Web Storage](https://en.wikipedia.org/wiki/Web_Storage), a key-value pair storage framework that provides behaviour similar to [cookies](https://en.wikipedia.org/wiki/HTTP_Cookie) but with larger storage capacity and improved API.
*   Web Workers
*   [Geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation) — get the latitude and longitude of the user’s browser
*   [File](https://developer.mozilla.org/en-US/docs/Web/API/File) — get file information from local files selected via file input, or drag and drop
*   [History](https://developer.mozilla.org/en-US/docs/Web/API/History) — add or remove URLs in the browser’s history stack — useful in single-page apps
*   Audio API
*   Video API

**Some more commonly used HTML APIs would be:**

*   [High-Resolution Time API](http://www.w3.org/TR/hr-time/): Provides the current time in the sub-millisecond resolution which is not dependent on the system clock
*   [Navigation Timing API](https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html): Offers detailed timing information throughout the page load process
*   [Network Information API](http://www.w3.org/TR/netinfo-api/). Provides estimation of bandwidth

> Know more about such APIs [here](https://www.sitepoint.com/10-html5-apis-worth-looking/).

**HTML APIs are also capable of creating responsive reusable layouts with Web Components which work similar way as APIs.**

For example the components like:

*   <dialog>: Display a popup or modal window without the overheads
*   <details> & <Summary>: Show/hide content under a collapsible heading without using JS
*   <picture>: To add responsive pictures which respond to different viewports and serve specialised content
*   <input>: to give instant feedback on form

These components can be used in any HTML file without copying the whole HTML file. Let’s know a little bit more about them.

Web Component and HTML API?
===========================


![Image for post](https://miro.medium.com/max/626/1*Wm4ExOqrH_evcssxiXtP6Q.png)

Web Components allow the developer to divide the HTML website into chunks of reusable customized code. These customized codes can be used in any part of the whole project without the requirement of copying the whole HTML file. It will help developers to write more modular code.

Building a Web Component uses four different specifications in the browser to construct, configure and generate their internal workings.

### HTML templates
HTML structure elements are often repeated to make sure each one works the same as the last. Instead, to save some time and reduce errors, we can also make a function to generate HTML for an element, adjusting the contents as they go. HTML templates bring that ability natively to browsers through use of the <template> element. The contents of a template stay inert and invisible, but JavaScript can access it like regular content without issue.

> Know more [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)

### Custom elements 
The most important feature of web components is the use of custom elements. As the name suggests, it helps the developer to create their own custom elements. They can also possess their own scripted behaviour and CSS styling.

> More info [here](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements)

### The Shadow DOM
The Document Object Model(DOM)represents each page as a set of connected elements. The shadow DOM is a hidden subset of further connections within a specific element of that DOM. Nothing inside the shadow DOM can affect anything outside. **For example**, a page may have an `<video>` element in its DOM, but the shadow DOM inside `<video>` houses the internal controls such as the play button and volume slider.

> Know more [here](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM)

### HTML Imports

HTML Imports allows the developer to import another HTML making the programmers’ life easier.

We can import HTML file by using <link> tag:

<link rel=”import” href=”main.html”>

> Find more HTML APIS [here](http://markapp.io/)


A simple HTML API Example:
==========================

Let’s create a syntax highlighting API for HTML code. We will write the JavaScript file in such a way that we won’t have to use any JavaScript code in the HTML. Plus the JS file will be reusable for multiple HTML files as well.

**App/main.js**
```
var para = document.querySelectorAll(“\[class^=highlight-\]”)  
var btn = document.querySelectorAll(“\[class^=highlight-button-\]”)btn\[0\].onclick = function(){ highlight();}function highlight(){  
    for(var i=0; i<para.length;i+=1){  
        var highlightColour = para\[i\].getAttribute(“data-color”);  
        para\[i\].style.color=highlightColour;  
    }  
}
```

Now, in JS file we are assuming every class getting started with “highlight-\*\*\*” to be a class to be highlighted and the colour of the highlight is be passed through “data-\* “ attribute.

So to include the same in HTML:

**App/index.html**
```
<!DOCTYPE html>  
<html>  
<style>  
body{  
  margin: 160px;  
  text-align: justify;  
}  
p{  
  font-size: 24px;  
}  
</style>  
<body>  
  <button class="highlight-button-1">Highlight</button>  
  <h1>Syntax Highlighting</h1> <p class="highlight-para1" data-color="green">Lorem ipsum dolor     sit amet, consectetur adipiscing elit. Fusce consectetur laoreet dui ac scelerisque.</p> <p class="highlight-para2" data-color="red">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce consectetur laoreet dui ac scelerisque.</p>
</body>

//adding API to the HTML file  
<script src="./main.js"></script></html>
```

You, see any element with the class name “highlight-\*\*\*” is by default being treated as an element for being highlighted. It doesn’t need any other settings or style customization. Here the main.js file is working as an HTML API.

![Image for post](https://miro.medium.com/max/2000/1*NQ-ePzR5PGWR-zd9IbeVpw.gif)

Now, this was an elementary example. We can also provide various settings with “data-\*” attribute for more styling and customization. Like this many APIs are built to provide more and more features to HTML elements. For example BootStrap, it provides both JS and CSS files to be added in HTML without the requirement of any customization.

Things to keep in mind while designing an HTML API:
===================================================

1.  Always try to use auto-initialize selectors for HTML elements
2.  The selectors need to be implicit
3.  A good practice is to allow these options to be used via either HTML or JavaScript, to accommodate both types of library users.
4.  Minimize Markup requirements. It’s a good idea to provide flexibility but writing too much markup is also annoying.
5.  Follow the conventions of HTML as much as possible
6.  It’s OK if not every single setting is available via HTML. The settings can also bet
7.  It’s good to have settings that can be inherited from ancestor elements if not from the exact elements
8.  Global Setting: the system should have two groups of settings: settings that customize how each instance of the widget behaves, and global settings that customize how the library behaves.

Resource:
---------

1.  [https://www.smashingmagazine.com/2017/02/designing-html-apis/](https://www.smashingmagazine.com/2017/02/designing-html-apis/)
2.  [https://www.admecindia.co.in/web-design/what-are-html5-apis-and-where-you-can-use-them/#](https://www.admecindia.co.in/web-design/what-are-html5-apis-and-where-you-can-use-them/#)
3.  [https://www.agitraining.com/html5/tutorials/html5-api-overview](https://www.agitraining.com/html5/tutorials/html5-api-overview)
4.  [https://www.creativebloq.com/features/best-html-apis](https://www.creativebloq.com/features/best-html-apis)

* * *

So that’s it for this article. I hope you all liked it and if you liked it then do not forget to tell us your thoughts in the comment section below.

> _If_ you want to connect with me, here I am at [Twitter](https://twitter.com/anishaswain) or [Instagram](https://www.instagram.com/anisha_swain_/)

Follow our community [LinkedIn group](https://www.linkedin.com/groups/13894715/), [Facebook](https://www.facebook.com/iamtheuigirl) Page and [Twitter](https://twitter.com/the_ui_girl) for more such articles and posts and meet like-minded people to collaborate.