Menu Close

Articles

JavaScript: web pages

A Web page is a document written or generated as HTML. When yo open the HTML is a text editor it looks alike a markup language. When you open the document in HTML it is parsed in memory and then rendered on the browser. 

Static web pages

A static web page is stored as file on server in a particular folder. The browser can find this folder by URL and search for a special file name: index.html. If this file is found it is send by the server to the browser for display. Sometimes the URL contains also the file-name and parameters for the server.

URL is a string, having this format:

  • protocol://domain/folder_name/file_name
  • protocol://domain/folder_name/file_name?param=value
  • protocol://domain/folder_name/file_name?param1=value&param2=value

A static web page do not need JavaScript. It can be plain HTML or it may contain CSS style. You can create “Static web pages” with basic HTML syntax and CSS.

Some HTML features:

  1. HTML document has hierarchical structure organized with “tags”,
  2. One tag has a beginning and an end that looks like this: <tag-name>content<tag-name/>,
  3. The tag name establish the element type: <div>, <p>, <ul>, <table> and so on,
  4. The content, can be another element or multiple elements separated by space or new line,
  5. Each element can have attributes: <element attribute=”value” attribute=”value” …>. 

Dynamic web pages

In addition to static web pages you must learn some additional HTML enhancements:

More HTML features:

  1. One HTML element can have a special kind of attribute is called “event attribute”,
  2. An event attribute value is representing a JavaScript function name with parameters,
  3. A special HTML element contain JavaScript code: <script>…<script>,
  4. JavaScript can be stored in external file, used in HTML with: <script src = “file.js”>.

The secret for dynamic web pages is in the Browser. That is the application used to render the HTML and display it on the screen. To do this, the Browser takes the documents and build in memory a model for it. This is called: Document Object Model (DOM).

DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript. After you modify DOM, the browser gets a notification and it will refresh the display representation of the web page.

To learn how to do this you must comprehend two things: First is the DOM representation structure. Second is the API (Application Programming Interface). The API is a set of functions implemented by JavaScript or other language to interact with DOM.

Document Object Model

DOM for short, is a tree structure. It has a root and nodes. The may contain other nodes. Each node has a specific type. There are two kind of relations between nodes: parent-child or sibling. When multiple nodes have same unique parent they are called sibling nodes and can be grouped together in an array.

DOM components:

ComponentDescription

Document

This object is the root document. 

Node

Every object is a node. It can be an element or text or attribute kind of node.

Element

The element is a node of type element. Elements are specialized: for instance, a <table> is of type HTMLTableElement.

NodeList

A nodeList is an array of elements. For instance the items in a <ol> ordered list or <ul> un-ordered list.  

Attribute

Attributes are nodes in the DOM just like elements are. The order of attributes in not relevant. 
NamedNodeMapA namedNodeMap is like an array, but the items are accessed by name.

Note: The relation between DOM components goes like this: Document -> Node -> NodeList -> Node -> Attribute. An element is a specialized node: Node -> Element.  

Application Programming Interface

API for short is a set of methods and properties you can use to access and manipulate DOM components. Components are objects implemented using OOP. So they may inherit common methods that look alike. Since most doom components are nodes, you have a common behavior, but each node is specialized so you may have additional API depending on node class.

Most common objects you are going to use in JavaScript are: Document, Window, Element.  The following is a brief list of common APIs in web and XML scripting using the DOM.

Document API:

  • document.getElementById(id)
  • document.querySelector(selector)
  • document.getElementsByTagName(name)
  • document.createElement(name)
  • parentNode.appendChild(node)

Element API:

  • element.innerHTML
  • element.style
  • element.setAttribute()
  • element.getAttribute()
  • element.addEventListener()

Window API:

  • window.content
  • window.onload
  • window.scrollTo()

External Reference: MDN Core Interfaces

What you can do with JavaScript?

Now you understand the basic idea to use JavaScript in HTML document. What else you can do?

  • You can find one element by Id,
  • You can find one or multiple elements by CSS selector,
  • You can create new elements,
  • You can remove elements,
  • You can hide elements from view,
  • You can show hidden elements,
  • You can change elements attributes and style,
  • You can associate functions to event attributes.

It may be intimidating, do not wary I will give you examples and explain it all one by one.

Find element by Id:

In next example you learn to use HTML and JavaScript together. You will create the <script> element at the end of HTML file to contain the JavaScript function. It is best to put your script at the end of HTML document, to improve performance.

Notes:

  • In HTML you can add attribute “id” to any element,
  • Attributes are always of type string, so you must use quotes to give a value “para”,
  • Finding an element by Id is the most precise method to find an element in DOM,
  • The “onclick” attribute is an “event attribute”. It is a trigger by the user with “mouse-click”.

Find element by selector:

To find an element by selector you can use two methods:

  • document.querySelector(selector)
  • document.querySelectorAll(selector)

The important part is: writing the selector such that will return your desired element and not another element by mistake. First function querySelector() will return one element, the first matching your selector. Second function will return multiple elements if multiple found. If no element is found the function will return: null.

Remember CSS selector:

You probably have forget what CSS selector is. Here is a short reminder for CSS selector notation:

  • hash “#” prefix represents the ID of element,
  • dot “.” prefix represents the class of element,
  • tag-name can be used as selector, represents all elements of a kind,
  • square parenthesis represents attribute based selector [attribute]
  • selectors can be combined with space or symbols: {, : . > = ~ *}

Example:

You can use CSS with the same selectors:

Of course the output will be color:

DIV FOO
DIV BAR

 

Homework:

  • You can try these snippets using following tool: https://codepen.io/pen/
  • To copy a snippet, first use double click then select, copy and paste each snippet.

The element

You may be not realizing yet, but finding an elements is the key for handle HTML. Once you found an element you can capture it in a variable, then use methods to change it as you wish. 

element.innerHTML

This property represents the content of an element. Usually is a text, that can be modified using direct assignment. 

element.style

After finding an element you can modify its style one value at a time or using cssText property.

Style properties:

Note: the property names are in camel-case and not kebab-case while setting the style.

Note: You can remove a style property by setting it to null: hello.style.color = null;

element.setAttribute()

You can add new attributes to an element. This may be for example “style”.

Create an event

If an element is found it can be modified so that it listen to events by using method AddEventListener()

Reference: MDN Event Listener

On load event

Until now you can see that JavaScript is executed in a web page immediate or on user click. It is possible though to start JavaScript with delay using “onload” event:

Example:

Note: The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

Read next: Forms