Dirk Harriman Banner Image

 

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.


 

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:

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:


 

 

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.

Browser Parts
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:

DOM 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:

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); });


 

Shopping Cart App