DOM

This section provides a brief introduction to Web development, specially focused on DOM, how to interact with it via JavaScript, and on Vue.JS Framework You can follow before the Khan Academy courses Intro to HTML/CSS: Making webpage and HTML/JS: Making webpages interactive You can read too the amazing book Speaking JS (free online) in order to have a good introduction to JavaScript. This course is based on this Mozilla tutorial

What is the DOM?

What is DOM? How it provides structure for HTML documents, how you can access it, and how this API presents the reference information and examples. The Document Object Model (DOM) is the data structure kept by the browser representing the webpage’s structure. DOM is a programming interface for HTML documents. It represents the page so that programs can change the document structure, style and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page and change it. A Web page is a document.The Document Object Model (DOM) represents that same page you can manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

The W3C DOM and WHATWG DOM standards are implemented in most modern browsers. Many browsers extend the standard. For example, the standard DOM specifies that the getElementsByTagName method in the code below must return a list of all the <P> elements in the document:

var paragraphs = document.getElementsByTagName("P");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);

All of the properties, methods, and events available for manipulating and creating web pages are organized into objects (e.g., the document object that represents the document itself, the table object that implements the special HTMLTableElement DOM interface for accessing HTML tables, and so forth).

DOM and JavaScript

The short example above, like nearly all of the examples in this reference, is JavaScript. That is to say, it’s written in JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn’t have any model or notion of web pages and their component parts (e.g. elements). Every element in a document - the document as a whole, the head, tables within the document, table headers, text within the table cells - is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:

API (HTML page) = DOM + JS (scripting language)

The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API.

How Do I Access the DOM?

You don’t have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible to script.

When you create a script–whether it’s inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.

This following JavaScript will display an alert when the document is loaded (and when the whole DOM is available for use).

<body onload="window.alert('Welcome to my home page!');">

This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document:

<html>
  <head>
    <script>
       // run this function when the document is loaded
       window.onload = function() {

         // create a couple of elements in an otherwise empty HTML page
         var heading = document.createElement("h1");
         var heading_text = document.createTextNode("Big Head!");
         heading.appendChild(heading_text);
         document.body.appendChild(heading);
      }
    </script>
  </head>
  <body>
  </body>
</html>

Core Interfaces in the DOM

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

Document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

The following is a brief list of common APIs in web and XML page scripting using the DOM.

document.getElementById(id)
document.getElementsByTagName(name)
document.createElement(name)
parentNode.appendChild(node)
element.innerHTML
element.style.left
element.setAttribute()
element.getAttribute()
element.addEventListener()
window.content
window.onload
window.dump()
window.scrollTo()

Testing the DOM API

This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser.

There are some cases, however, when the examples are more concise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to call those functions from the browser.

You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the test() function as needed, create more buttons, or add elements as necessary.

<html>
  <head>
    <title>DOM Tests</title>
    <script type="application/javascript">
    function setBodyAttr(attr, value){
      if (document.body) eval('document.body.'+attr+'="'+value+'"');
      else notSupported();
    }
    </script>
  </head>
  <body>
    <div style="margin: .5in; height: 400;">
      <p><b><tt>text</tt></b></p>
      <form>
        <select onChange="setBodyAttr('text',
        this.options[this.selectedIndex].value);">
          <option value="black">black
          <option value="darkblue">darkblue
        </select>
        <p><b><tt>bgColor</tt></b></p>
        <select onChange="setBodyAttr('bgColor',
        this.options[this.selectedIndex].value);">
          <option value="white">white
          <option value="lightgrey">gray
        </select>
        <p><b><tt>link</tt></b></p>
        <select onChange="setBodyAttr('link',
        this.options[this.selectedIndex].value);">
          <option value="blue">blue
          <option value="green">green
        </select>  <small>
        <a href="http://www.brownhen.com/dom_api_top.html" id="sample">
        (sample link)</a></small><br>
      </form>
      <form>
        <input type="button" value="version" onclick="ver()" />
      </form>
    </div>
  </body>
</html>

To test a lot of interfaces in a single page-for example, a "suite" of properties that affect the colors of a web page-you can create a similar test page with a whole console of buttons, textfields, and other HTML elements. The following screenshot gives you some idea of how interfaces can be grouped together for testing.

JavaScript & cie

Build JS tooling

You can use several tools to automate your front-end builds. This allows for better code management, CI integration, and convenience. Tools examples : Grunt, Bower, Gulp, Webpack

Ajax & JSON

Ajax = "Asynchronous JavaScript And XML". Ajax is a set of Web development techniques using many Web technologies on the client side to create asynchronous Web applications. You can send data to and retrieve from a server asynchronously (in the background) with Ajax. With Ajax, you dedicate a layer for the data interchange, distinct from the presentation layer. Ajax allows, with that, to change content dynamically without the need to reload the entire page. It was with the advent of Ajax in 1999 (standardised in 2006) that JavaScript started to grow. Before Ajax, JavaScript was mostly used to animate and provide interactivity to some webpages, without involve interchanging data with the server. With Ajax, JavaScript started to perform key tasks in our web-applications application-logic, to the point that nowadays it’s hard to find web-applications that do not require a JavaScript-enabled browser in order to work. It was after this change that the JavaScript ecosystem started to expand as a client-side programming language. Modern implementations commonly substitute JSON for XML due to the advantages of being native to JavaScript.

JSON = "JavaScript Object Notation".

JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation. When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. We can also convert any JSON received from the server into JavaScript objects. This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

JavaScript ecosystem

The main needs of the developers working with AJAX web applications are:

  • Performing Ajax calls

  • Manipulating the DOM

  • React to the user’s interactions

The core JavaScript functions providing these features were not very practical to be used and sometimes their behaviour was not compatible with different browsers. The first libraries to become popular addressed precisely these three tasks, providing a collection of functions and objects that made these operations easy and functional on every browser. Some of these libraries would also provide plenty of other general-purpose functions.

  • JQuery

  • MVC-Like Frameworks : Angular, React, Vue

it’s increasingly popular not to use jQuery and to rather rely on either only the current core JavaScript functions or on libraries that are specialised in each specific task (e.g. fetch for AJAX calls). The jQuery framework was released in 2006 and has let the language core as it were and rather focused on providing plenty functionalities related with the DOM, events, asynchronicity and effects. One feature to highlight is that jQuery sports a plugin system that allows library programmers to extend its functionality. This library was the most successful library of this kind, being used nowadays in the majority of the websites. Despite jQuery’s immense popularity, as well as its ability to provide many useful functionalities, it’s important to notice that modern versions of JavaScript already provide many of the functionalities that made jQuery popular.

While using DOM-Manipulation libraries it’s common to keep the application data in the DOM itself, thus there are DOM-Manipulation selector functions that have to be called when needing to access or modify this data. This kind of code is often filled with selector-names and easily becomes a mess as the application’s complexity evolves. There is a set of frameworks that allow us to address this problem in an elegant way by leveraging on application patterns that are similar to the famous Model-View-Controller (MVC) pattern. On the other hand, there is a recent trend in which web-applications are fully loaded in the browser on the first page-load, performing every subsequent operations via Ajax. This kind of applications is called Single-Page Application (SPA) and, as their code is often quite elaborate and complex, it’s recommendable to pick one of these frameworks, like Angular, when implementing a SPA. You can read a good comparison of Angular, React and Vue here.

Vue.Js

What is Vue.js?

Vue (pronounced like "view") is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

Now read the Vue.js guide

How to call an API ?

Axios is a great http client library. You can use it to manage your API calls. It uses promises by default. A Promise is a JavaScript object representing the eventual completion or failure of an asynchronous operation. A promise may be created using its constructor. However, most people are consumers of already-created promises returned from functions.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

E.g., instead of an old-style function that expects two callbacks, and calls one of them on eventual completion or failure:

function successCallback(result) {
  console.log("It succeeded with " + result);
}

function failureCallback(error) {
  console.log("It failed with " + error);
}

doSomething(successCallback, failureCallback);
  1. modern functions return a promise you can attach your callbacks to instead:

let promise = doSomething();
promise.then(successCallback, failureCallback);
  1. or simply:

doSomething().then(successCallback, failureCallback);

We call this an asynchronous function call.

Axios is also quite easy to use with Vue. Because it uses promises, you can combine it with async/await to get an amazingly concise and easy-to-use API.

Now? It’s your turn : try to develop this page, which will use your API services deployed on Heroku.