Notes Javascript - Client-Side Web APIs
Client-Side Web APIs
Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily. They abstract more complex code away from you, providing some easier syntax to use in its place.
- JavaScript - A high-level scripting language built into browsers that allows you to implement functionality on web pages/apps. Note that JavaScript is also available in other programming environments, such as Node.
- Browser APIs - constructs built into the browser that sits on top of the JavaScript language and allows you to implement functionality more easily.
- Third-party APIs - constructs built into third-party platforms (e.g. Twitter, Facebook) that allow you to use some of those platform's functionality in your own web pages (for example, display your latest Tweets on your web page).
- JavaScript libraries - Usually one or more JavaScript files containing custom functions that you can attach to your web page to speed up or enable writing common functionality. Examples include jQuery, Mootools and React.
- JavaScript frameworks - The next step up from libraries, JavaScript frameworks (e.g. Angular and Ember) tend to be packages of HTML, CSS, JavaScript, and other technologies that you install and then use to write an entire web application from scratch. The key difference between a library and a framework is "Inversion of Control". When calling a method from a library, the developer is in control. With a framework, the control is inverted: the framework calls the developer's code.
Common Browser APIs
In particular, the most common categories of browser APIs you'll use (and which we'll cover in this module in greater detail) are:
- APIs for manipulating documents loaded into the browser. The most obvious example is the DOM (Document Object Model) API, which allows you to manipulate HTML and CSS - creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page or some new content displayed, for example, that's the DOM in action. Find out more about these types of API in Manipulating documents.
- APIs that fetch data from the server to update small sections of a webpage on their own are very commonly used. This seemingly small detail has had a huge impact on the performance and behavior of sites - if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy". The main API used for this is the Fetch API, although older code might still use the XMLHttpRequest API. You may also come across the term Ajax, which describes this technique. Find out more about such APIs in Fetching data from the server.
- APIs for drawing and manipulating graphics are widely supported in browsers - the most popular ones are Canvas and WebGL, which allow you to programmatically update the pixel data contained in an HTML <canvas> element to create 2D and 3D scenes. For example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and textures using WebGL. Such APIs are often combined with APIs for creating animation loops (such as window.requestAnimationFrame()) and others to make constantly updating scenes like cartoons and games.
- Audio and Video APIs like HTMLMediaElement, the Web Audio API, and WebRTC allow you to do really interesting things with multimedia such as creating custom UI controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing video from your web camera to be manipulated via a canvas (see above) or displayed on someone else's computer in a web conference, or adding effects to audio tracks (such as gain, distortion, panning, etc.).
- Device APIs enable you to interact with device hardware: for example, accessing the device GPS to find the user's position using the Geolocation API.
- Client-side storage APIs enable you to store data on the client-side, so you can create an app that will save its state between page loads, and perhaps even work when the device is offline. There are several options available, e.g. simple name/value storage with the Web Storage API, and more complex database storage with the IndexedDB API.
Common Third-Party APIs
Third-party APIs come in a large variety; some of the more popular ones that you are likely to make use of sooner or later are:
- The Twitter API, which allows you to do things like displaying your latest tweets on your website.
- Map APIs, like Mapquest and the Google Maps API, which allow you to do all sorts of things with maps on your web pages.
- The Facebook suite of APIs, which enables you to use various parts of the Facebook ecosystem to benefit your app, such as by providing app login using Facebook login, accepting in-app payments, rolling out targeted ad campaigns, etc.
- The Telegram APIs, which allows you to embed content from Telegram channels on your website, in addition to providing support for bots.
- The YouTube API, which allows you to embed YouTube videos on your site, search YouTube, build playlists, and more.
- The Pinterest API, which provides tools to manage Pinterest boards and pins to include them in your website.
- The Twilio API, which provides a framework for building voice and video call functionality into your app, sending SMS/MMS from your apps, and more.
- The Mastodon API, which enables you to manipulate features of the Mastodon social network programmatically.
How Do APIs Work?
Different JavaScript APIs work in slightly different ways, but generally, they have common features and similar themes to how they work.
They Are Based On Objects
Your code interacts with APIs using one or more JavaScript objects, which serve as containers for the data the API uses (contained in object properties), and the functionality the API makes available (contained in object methods).
They Have Recognizable Entry Points
When using an API, you should make sure you know where the entry point is for the API. In The Web Audio API, this is pretty simple — it is the AudioContext object, which needs to be used to do any audio manipulation whatsoever.
They Often Use Events To Handle Changes In State
Some web APIs contain no events, but most contain at least a few. The handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "Event handlers" sections.
They Have Additional Security Mechanisms Where Appropriate
WebAPI features are subject to the same security considerations as JavaScript and other web technologies (for example same-origin policy), but they sometimes have additional security mechanisms in place. For example, some of the more modern WebAPIs will only work on pages served over HTTPS due to them transmitting potentially sensitive data (examples include Service Workers and Push).
Parts Of A Browser
Web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security.
The window | The window is the browser tab that a web page is loaded into; this is represented in JavaScript by the Window object. Using methods available on this object you can do things like return the window's size (see Window.innerWidth and Window.innerHeight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. |
---|---|
The navigator | The navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. In JavaScript, this is represented by the Navigator object. You can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc. |
The document | The document (represented by the DOM in browsers) is the actual page loaded into the window, and is represented in JavaScript by the Document object. You can use this object to return and manipulate information on the HTML and CSS that comprises the document, for example get a reference to an element in the DOM, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether. |
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Simple DOM example</title> </head> <body> <section> <img src="dinosaur.png" alt="Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms." /> <p> Here we will add a link to the <a href="https://www.mozilla.org/">Mozilla homepage</a> </p> </section> </body> </html>
The DOM
The DOM (Document Object Model) is represented by a tree of nodes. Nodes are referred to by their position in the tree relative to other nodes:
Root Node |
The top node in the tree, which in the case of HTML is always the HTML node (other markup vocabularies like SVG and custom XML will have different root elements). |
---|---|
Child Node | A node directly inside another node. For example, IMG is a child of SECTION in the above example. |
Descendant Node |
A node anywhere inside another node. For example, img is a child of section in the above example, and it is also a descendant. img is not a child of body, as it is two levels below it in the tree, but it is a descendant of body. |
Parent Node | A node which has another node inside it. For example, body is the parent node of section in the above example. |
Sibling Nodes | Nodes that sit on the same level in the DOM tree. For example, img and p are siblings in the above example. |
Basic DOM Manipulation
To manipulate an element inside the DOM:
1. Select the element you want to manipulate by getting a reference to it.
This can be done in several ways:
document.querySelector(selctorString)
document.querySelectorAll(selctorString)
document.getElementById(IdString)
document.getElementByTagName(TagString)
document.getElementByClassName(ClassString)
2. Creating and placing new nodes
// GET A REFERENCE TO THE FIRST <section> const sect = document.querySelector("section"); // CREATE A NEW PARAGRAPH <p> ELEMENT const para = document.createElement("p"); // ADD SOME TEXT TO THE PARAGRAPH para.textContent = "Some text here."; // APPEND IT TO THE SECTION sect.appendChild(para); // CREATE A NEW TEXT NODE const text = document.createTextNode(" - more text at the end."); // GET A REFERENCE TO THE FIRST <p> ELEMENT const linkPara = document.querySelector("p"); // APPEND THE TEXT NODE TO THE PARAGRAPH linkPara.appendChild(text);
3. Moving & Removing Elements
Removing a node is pretty simple as well, at least when you have a reference to the node to be removed and its parent. In our current case, we just use Node.removeChild(), like this:
sect.removeChild(linkPara);
When you want to remove a node based only on a reference to itself, which is fairly common, you can use Element.remove():
linkPara.remove();
This method is not supported in older browsers. They have no method to tell a node to remove itself, so you'd have to do the following.
linkPara.parentNode.removeChild(linkPara);
4. Manipulating Styles
para.style.color = "white"; para.style.backgroundColor = "black"; para.style.padding = "10px"; para.style.width = "250px"; para.style.textAlign = "center";
5. Manipulating Attributes
para.setAttribute("class", "highlight");
In this case the attribute manipulated is the class. Elements have other attributes that can be manipulated such as a data attribute.
Shopping List Application
A simple shopping list example that allows you to dynamically add items to the list using a form input and button. When you add an item to the input and press the button:
- The item should appear in the list.
- Each item should be given a button that can be pressed to delete that item off the list.
- The input should be emptied and focused ready for you to enter another item.
window.addEventListener("DOMContentLoaded", (event) => { (function (w, $) { // UL, INPUT AND BUTTON let ulShoppingList = document.getElementById("ulShoppingList"); let txtShoppingItem = document.getElementById("txtShoppingItem"); let btnAddItem = document.getElementById("btnAddItem"); const addListItem = function() { // GET THE TEXT IN THE TEXTBOX let newItem = txtShoppingItem.value; // EMPTY THE CONTENTS OF THE TEXTBOX txtShoppingItem.value = ""; // CREATE NEW LI, SPAN AND BUTTON ELEMENTS const elLi = document.createElement("li"); const elSpan = document.createElement("span"); const elBtn = document.createElement("button"); // APPEND SPAN AND BUTTON TO LIST ITEM elLi.appendChild(elSpan); elLi.appendChild(elBtn); // SET THE TEXT OF THE SPAN TO THE SAVED TEXT FROM THE TEXTBOX elSpan.textContent = newItem; // SET THE TEXT OF THE BUTTON TO DELETE elBtn.textContent = "Delete"; // SET THE CLASS FOR THE DELETE BUTTON elBtn.setAttribute("class", "btn btn-sl-primary"); // ADD THE LIST ITEM TO THE LIST ulShoppingList.appendChild(elLi); // DELETE BUTTON CLICK EVENT elBtn.addEventListener("click", () => { ulShoppingList.removeChild(elLi); }); txtShoppingItem.focus(); }; btnAddItem.addEventListener("click", addListItem); // ENABLE THE LIST TO BE BUILT BY JUST HITTING THE RETURN KEY txtShoppingItem.addEventListener("keyup", (e) => { if (e.keyCode == 13) { addListItem(); } }); })(window, jQuery); });