Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Links | Search | Bio |

Guide to HTML, CSS, and JavaScript (University at Buffalo Version)


Chapter 10: Creating a JavaScript Web Page

When you create a web page made up of HTML and CSS you are creating a rather *static* web page. Quite often though you will need to add features to you web page to make it a little more dynamic, such as form validation, data manipulation, or something simply like displaying the current date. JavaScript is a coding language that can be either embedded right inside your HTML code or included using the <script> tag to reference an external JavaScript (*.js*) file.

The HTML <script> ... </script> Tags

For example, if you want to include the current date you could use this line in the <body> area of your HTML code:

<script>
  document.write("<span style='font-size: 6pt;'>" + Date() + "</span>");
</script>

Figure 10-1: HTML <script> Tag

The id="" Identifier Atribute

I use document.write in my examples. However, a better, way to do this would be to define an identifier (id="") for the container (div or p or span) and use JavaScript to update that container with the current date:

<div id="currentDate"></div>
<script>
  document.getElementById("currentDate").innerText = (new Date()).toDateString();
</script>

Figure 10-2: Modify Page with JavaScript

JavaScript Comments

Adding comments to your code can help you remember what your code is doing at that statement and will also help others who may need to maintain your code in the future.

JavaScript has two (2) different comment statements. The /* */ can be used to have multiple lines. For example:

/*
Assignment: Form Web Page
Author: Your Name Here
Date: Month Day, Year file was last edited
Editor: Notepad++ or TextWrangler or whatever editor you used
*/


Figure 10-3: Multi-line JavaScript Comments

The // can be used for an inline or single line comment (I would have a <div id="myLoop"></div> in my HTML code):

var i; // Declare a variable named i to be used in a for loop
for (i = 0; i < 12; i++) {
  document.getElementById("myLoop").innerHTML = "i = " + i + "<br />\n";
}

Figure 10-4: Inline JavaScript Comments

JavaScript Functions

JavaScript functions provide a way to perform a task. Functions are useful when you have a set of statements that you would like to be able to use more than once. Functions allow to reduce the use of duplicate code.

A JavaScript function begins with the word function followed by the name of the function and then a set of statements enclosed between n opening right brace ({) and a closing left brace (}). For example:

/*
This function accepts 2 parameters and returns the sum of those 2 values
*/

function addTwo(num1, num2) {
  return num1 + num2;
}

Figure 10-5: A JavaScript Function

To *call* (execute) your functon you simply use the function name and pass any needed parameters. I would have a <div id="myFunction"></div> in my HTML code.

<script>
  var firstNum = 10;
  var secondNum = 20;
  document.getElementById("myFunction").innerHTML = firstNum " + " secondNum, " = <b>" + addTwo(firstNum, secondNum) + "</b>";
</script>

Figure 10-6: Calling the addTwo() JavaScript Function
10 + 20 = 30

Figure 10-7: The JavaScript addTwo() Function Output

Using the <script> ... </script> Tag to Include a JavaScript File

You can also create an external file to store your JavaScript functions, for example: *myFunctons.js*. This is especially useful if you want to use that same JavaScript in multiple web pages. For an external JavaScript file you would add this <script> tag to the <head></head> area of your HTML file:

<head>
  <script src="myFunctions.js"></script>
</head>

Figure 10-8: Using the HTML <script> ... </script> Tags

JavaScript Arrays

Like most languages, JavaScript provides arrays to store multiple values in a single array variable.

An array in JavaScript is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. The first element of an array is referenced as the zero (0 element. For example (I would have a <div id="myArray"></div> in my HTML code):

var arr = [6, 8, 2, 1, 4, 10, 3, 13, 11, 7];
for (var i = 0; i < arr.length; i++) {
  document.getElementById("myArray").innerHTML = "Array element i = " + arr[i] + "<br />\n";
}

Figure 10-9: A JavaScript Array


Figure 10-10: Print Array

An associative array allows you to access the array elements using a keyword/value pair. For example (I would have a <div id="myStates"></div> in my HTML code):

var statesArray = ['AK' : 'Alaska', 'AL' : 'Alabama', 'AR' : 'Arkansas', 'AZ' : 'Arizona'];
for (var name in statesArray) {
  document.getElementById("myStates").innerHTML = "Name: " + statesArray[name] + " = (" + name + ")<br />\n";
}

Figure 10-11: A JavaScript Associative Array


Figure 10-12: Print Associative Array

Sorting JavaScript Arrays

JavaScript provides a many functons for sorting arrays. The .sort() method sorts an array in ascending order and the .reverse() method sorts an array in reverse order. I would have a <div id="myAssoc"></div> in my HTML code.

var statesArray = {"Ohio","Florida","Massachusetts","Montana"};
sortHTML = "<b>Before sort:</b> ";
for (var i = 0; i < statesArray.length; i++) {
  sortHTML += "Array element " + i + " = " + statesArray[i] + "<br />\n";
}
statesArray.sort();
sortHTML += "<br />\n<b>After sort:</b> ";
for (var i = 0; i < statesArray.length; i++) {
  sortHTML += "Array element i = ", statesArray[i], "<br />\n";
}
document.getElementById("myAssoc".innerHTML = sortHTML;

Figure 10-13: Using .sort() to Sort an Array


Figure 10-14: Sort an Array Output
var statesArray = {"Ohio","Florida","Massachusetts","Montana"};
document.write("<b>Before sort:</b> ");
for (var i = 0; i < statesArray.length; i++) {
  document.write("Array element ", i, " = ", statesArray[i], "<br />\n");
}
statesArray.reverse();
document.write("<br />\n<b>After sort:</b> ");
for (var i = 0; i < statesArray.length; i++) {
  document.write("Array element i = ", statesArray[i], "<br />\n");
}

Figure 10-15: Using .reverse() to Reverse Sort an Array


Figure 10-16: Reverse Sort an Array Output

Using the Browser Developer tools Console Tab

All major web browsers (Chrome, Edge, Firefox, IE, Opera, and Safari, provide Developer Tools that allow you to use the Console tab to view and JavaScript errors.

Edge or IE
Press F12 and open the Developers Tools to view the JavaScript Console.
Chrome, Firefox, or Opera
Press CTRL-Shift-I to open the Developer Tools to view the JavaScript Console.
Safari
Press CTRL-Alt-I to open the Developer Tools to view the JavaScript Console.

You can use the JavaScript console.log("some string") method to log a debug message that you can see in the Browser Developers Tools Console to help debug your JavaScript code.

Console Tab

Figure 10-17: Using the Browser Developer tools Console Tab

For more information about JavaScript use your favorite search engine (Bing, Google, Yahoo, etc.) and search for:

javascript tutorials for beginners

Task - Create a JavaScript Web Page

For this task you will create a new web page file just as you did in previous tasks. This web page should use JavaScript functions to include the following:

  1. Display the current date
    • Display the current time
    • Create a variable, dueDate, that stores a date 6 days after the date you started this task
    • Uses an if construct based on the dueDate and the current date to print out either:
      how many days are left until this task is due
      or
      how many days have past since this task was due
  2. Display a table that has 12 rows and 3 columns which is created using a for loop to read through a set of JavaScript arrays that contain the names of the months and the number of days in each month.
  3. Uses the JavaScript mod operator (%) to highlight every other row of the above table with a different color to make it easier to read. The table should look similar to this:

    Months Table

Hint: if you use the JavaScript mod operator (%) to divide the loop counter by 2 and there is no remainder that means the loop counter is an even number and so you need to highlight that row.

This web page should also have a link back to your Home Page task web page.

You should then add an <a> (anchor) tag to your Home Page web page that opens your advanced CSS web page.

Let's Get Started with a JavaScript Table Page!

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland