Sage-Code Laboratory
index<--

JavaScript Website

A Web page is a document written or generated as HTML. When yo open the HTML file using a text editor it looks like a markup language. However, when you open the document in the Browser it is parsed in memory and then rendered. During rendering the HTML tags, images and css are all interpreted to create nice web pages.

Page bookmarks

Static web pages

A static web page consist of HTML files, Image files, Media files and CSS files. All these can be stored together on a single folder or can be distributed in several folders.The main page or the default page is called usually "index.html". If this page exist this is the first open to see the content. Other pages may be connected to index page using a chain of links. A static web page do not need JavaScript.

Hosting a website

To make a website you can edit the folder structure and the condent local on your computer.After you finish you can upload all content file by file to a server. Once the files are on the server, other people can visit your vebsite and see the content.It depends on the hosting plan where you should upload your files.This website is served by "Apache" that is an open source applica server. My defaul folder is called "public_html". In this folder I have created subfolder: /script.

Domain and URL

It is not easy to purcese a hosting plan. You must know exactly what you are looking for so that you do not waste your money. To host a website on the internet you need a domain name. This will be used to create links and URL addresses. When you design a website you can use relative links to connect pages and images together. Visitors will need the link to the first page. The other pages will be visited using relative links.

URL is a string, having this format:

url anathomy

URL Anathomy

Static HTML document

A static website is based on static HTML documents. These are files that hold text content and organize the display of the content using HTML tags. You have to learn HTML before you learn how to do a website.

Dynamic HTML document

In addition to static web pages you must learn some new HTML elements. These can be new tags and new attributes that we need to enhance the HTML pages for JavaScript interaction. Once we have design a page for JavaScript, we can interact with HTML and control its content using coding.

More HTML features:

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

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 modify DOM dynamicly you learn: First the DOM structure. Second, the API (Application Programming Interface). The Browser API is a set of functions, implemented for JavaScript or other language to interact with DOM.

Document Object Model

DOM for short, is a logic 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:

Component Description
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: of type HTMLTableElement.
NodeList A nodeList is an array of elements 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.
NamedNodeMap A 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

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.

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

Element API:

Window API:

External Reference:  MDN Core Interfaces

What else you can do?

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

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.

<html>
<head>
   <title>getElementById example</title>
</head>
<body>
   <p id="para">Some text here</p>
   <button onclick="changeColor('blue');">blue</button>
   <button onclick="changeColor('red');">red</button>
</body>
<script>
   function changeColor(newColor) {
       var elem = document.getElementById('para');
       elem.style.color = newColor;
   }
</script>
</html>

Notes:

Find element by selector:

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

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.

Review CSS selectors

You probably have forget what CSS selector is it true? Here is a short reminder for CSS selector notation:

Example:

<div id="foo"></div>
<div class="bar"></div>
<script>
   document.querySelector('#foo').innerHTML = "DIV FOO";
   document.querySelector('.bar').innerHTML = "DIV BAR";
</script>

You can use CSS with the same selectors:

#foo {
   color: red;
   background: silver;
}
.bar {
   color: yellow;
   background: green;
}

Of course the output will be color but this stupid GitHub can not render colors so I have to insert a small image here to show you the result of our example:

Homework:

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 its handler in a variable, then use methods to change it as you wish.You must also know some properties that are useful for programming HTML with JavaScript code.

One of the important properties you need to learn: element.innerHTML property
This property represents the content of an element. Usually is a text, that can be modified using direct assignment.

<html>
   <body>
       <p id="hello">...</p>
   <body>
   <script>
      hello = document.getElementById("hello");
      hello.innerHTML = "hello world";
   </script>
</html>

element.style

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

<html>
    <body>
        <p id="hello">Hello World!</p>
    <body>
    <script>
        hello = document.querySelector("#hello");
        hello.style.cssText= "color:green; font-weight:bold";
    </script>
</html>

style properties

After you find an element you can change its style:

<html>
    <body>
        <p id="hello">Hello World!</p>
    <body>
    <script>
        hello = document.querySelector("#hello");
        hello.style.color= "green"
        hello.style.fontWeight = "bold";
    </script>
</html> 

Notes: 

element.setAttribute()

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

<html>
    <body>
    <p id="hello">Hello World!</p>
    </body>
    <script>
      hello = document.querySelector("#hello")
      hello.setAttribute("style","color:green; font-weight:bold")
    </script>
</html>

Create an event

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

<html>
   <body>
       <div id="test">click me!</div>
   </body>
   <script>
       // change the content of #test
       function modifyText() {
           let test = document.getElementById("test");
           if (test.innerText == "click me!")
               test.innerText = "click again!";
           else
               test.innerText = "click me!";
       }
       // add event listener
       let elm = document.getElementById("test");
       elm.addEventListener("click", modifyText, false);
   </script>
<html>

External 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. We can use this event to start a javaScript function after the page finish loading.

Example:

<html>
<head>
    <script>
        function load() {
          console.log("page is loaded!");
        }
        window.onload = load;
    </script>
<head>
<body>
    <p>Hello World!</p>
</body>
</html>

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. So the onload function can stay anywehere in the document, including in the header.

JavaScript Code

The JavaScript computer language is used to create scripts rather than large and monolithic applications. Usually a script is part of a HTML web page but can also be a separate file with extension *.jsSome web applications are using just one or two *.js files. These are text files and relative small.

Script Element

We can use tags: <script> ... </script> to insert JavaScript code into HTML pages. One HTML page can contain many scripts. Each script must be enclosed into <script> tags.Default scripting language for web pages is JavaScript but it is possible to use other computer languages in HTML web pages using the "script" tags. Script can be located in HTML "head" or "body".

Example:

In this example JavaScript is stored in the "head" element of HTML.

<!DOCTYPE html>
<html>
<head>
    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = "Paragraph changed.";
        }
    </script>
</head>
<body>
    <h1>My Web Page</h1>
    <p id="demo">A Paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Caution: A script can modify HTML elements only after they are defined. So the script location is important. If you define the script earlier it will not have access to all page elements.

Script location:

In HTML document we nest one element in other element. So the "script" can be nested insite the "head" element or the "body" element. Web developers prefer to implement JavaScript in the "body"region of HTML. This is to allow a faster rendering of the page. JavaScript must be compiled and is better to compile the script after the page is loaded.

Example2:

In this example JavaScript is located in the "body" element.

<!DOCTYPE html>
<html>
<body>
    <h1>My Web Page</h1>
    <p id="demo">A Paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
         document.getElementById("demo").innerHTML = "Paragraph changed.";
        }
    </script>
</body>
</html>
Performance: Loading javascript in the "body" can make web page load faster.The page can be display early and javascript will continue to load in the background.Of course you can not use JavaScript functions that are not yet loaded. Doing so will trigger an error.

External Scripts

We can create JavaScript files with extension js that are loaded in HTML pages using "script" tag with attribute "src" like this:

<script src="sourge_file.js">

Example:

In this example JavaScript myFunction is hooked to an click event of the button. When user press the button the function is executed.

<!DOCTYPE html>
<html>
<body>
    <h1>External JavaScript</h1>
    <p id="demo">A Paragraph.</p>
    <button type="button" onclick="myFunction()">Try it</button>
    <p> Note: myFunction is stored in an external file called "myScript.js".</p>
    <script src="myScript.js"></script>
</body>
</html>

Externa file: "myScript.js" contain the declaration for function myFunction().

/* external file */
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}

Advantages:

Placing JavaScripts in external files has some advantages:


Read next: Libraries