Module 4 - JavaScript
Module 4 - JavaScript
Make it interactive!
The structure and aesthetic design of a website make it visually appealing and enticing to
visitors. But, by that alone, there is really nothing more to it than just a piece of art.
There are actually many components needed to make a functional website to bring out that
excitement but there is one that serves as a good starting point to inject life to your static
web pages and that is JavaScript. It allows you to implement complex features on web page
such as displaying timely content updates, interactive maps, animated 2D/3D graphics, etc.
The sections in this module will help you learn more about JavaScript.
What is JavaScript?
The idea was that major interactive parts of the client-side web were to be implemented in
Java. JavaScript was supposed to be a glue language for those parts and to also make HTML
slightly more interactive. Given its role of assisting Java, JavaScript had to look like Java.
That ruled out existing solutions such as Perl, Python, TCL, and others.
JavaScript Versions
JavaScript was invented by Brendan Eich in 1995, and became a standard for performing
computations in Web Applications in 1997 adopted by the European Computer
Manufacturer’s Association (ECMA). Hence, ECMAScript is the official name of the language.
ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6. Since 2016 new
versions are named by year (ECMAScript 2016 / 2017 / 2018).
The following popular web browsers support JavaScript but Chrome and Firefox are
notably the first to adapt new features after its release.
Embedding JavaScript
You can place any number of scripts in an HTML document. Scripts can be placed in
the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script>
alert("Hello World! I am an alert box.");
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
</body>
</html>
JavaScript in <body>
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h2>JavaScript in Head</h2>
<script>
alert("Hello World! I am an alert box.");
</script>
</body>
</html>
JS scripts can also be placed in external files. External scripts are practical when the same
code is used in many different web pages. Each external file that contains your JS scripts must
have the file extension .js. To use an external script, put the name of the script file in the src
(source) attribute of a <script> tag:
<script src="myScript.js"></script>
Similarly, you can place an external script reference in <head> or <body> as you like. The
script will behave as if it was located exactly where the <script> tag is located.
To add several script files to one page - use several script tags:
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
<script src="https://www.example.com/js/myScript.js"></script>
<script src="/js/myScript.js"></script>
<script src="myScript.js"></script>
The Fundamentals of Code
JavaScript is one of the most popular modern web technologies! As your JavaScript skills
grow, your websites will enter a new dimension of power and creativity.
However, getting comfortable with JavaScript is more challenging than getting comfortable
with HTML and CSS. You may have to start small, and progress gradually. To begin, let's
examine how to add JavaScript to your page by creating a Hello world! exercise.
1. Open your index.html from the previous modules and insert a pair of
<script></script> tags before the closing head tag of your page as shown below.
<head>
.........
.........
<script>
</script>
</head>
<script>
alert("Hello World! I am an alert box.");
</script>
3. Once everything is in order, load the page in your browser and an alert message box
should pop-up over your page, like in the image below.
If you have seen the alert message you have successfully embedded JavaScript in
your page. What a good way to start!
Message Boxes - Alerts, Confirms and Prompts
JavaScript provides built-in global functions to display messages to users for different
purposes, e.g., displaying a simple message or displaying a message and take the user's
confirmation or displaying a popup to take the user's input value.
Alert Box
Use the alert() function to display a message to the user that requires their attention. This
alert box will have the OK button to close the alert box.
The alert() function takes a parameter of any type e.g., String, Number, Boolean etc. So, no
need to convert a non-string type to a string type.
Confirm Box
Sometimes you need to take the user's confirmation to proceed. For example, you want to
take the user's confirmation before saving updated data or deleting existing data. In this
scenario, use the built-in function confirm().
The confirm() function displays a popup message to the user with two
buttons, OK and Cancel. The confirm() function returns true if a user has clicked on
the OK button or returns false if clicked on the Cancel button. You can use the return value
to process further.
var choice;
Prompt Box
Syntax
The prompt() function takes two string parameters. The first parameter is the message to be
displayed, and the second parameter is the default value which will be in input text when the
message is displayed.
if (tenure != null) {
alert("You are " + tenure + "years old");
}
JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores the data value that
can be changed later on.
var <variable-name>;
var <variable-name> = <value>;
Examples
Variable Scope
In JavaScript, a variable can be declared either in the global scope or the local scope.
Global Variables
Variables declared out of any function are called global variables. They can be
accessed anywhere in the JavaScript code, even inside any function.
Local Variables
Variables declared inside the function are called local variables to that
function. They can only be accessed in the function where they are declared
but not outside.
function myfunction(){
var name = "Vince!";
alert(greet + name); //can access global and local
variable
}
myfunction();
Variable names are case-sensitive in JavaScript. So, the variable names name, NAME,
Name, nAme are considered separate variables.
Variable names can contain letters, digits, or the symbols $ and _.
A variable name cannot start with a digit 0-9.
A variable name cannot be a reserved keyword in JavaScript, e.g. var, function,
return cannot be variable names.
JavaScript includes data types similar to other programming languages like Java or C#.
JavaScript is dynamic and loosely typed language. It means you don't require to specify a
type of a variable. A variable in JavaScript can be assigned any type of value, as shown in the
following example.
Type Example/Usage
str[0] // H
str[1] // e
str[2] // l
String
str[3] // l
str[4] // o
str.length // 11
if(YES){
alert("This code block will be executed");
Boolean }
if(NO){
alert("This code block will not be executed");
}
Arithmetic Operators
Operator Example/Usage
+ var x = 5, y = 10;
Addition
var z = x + y; //performs addition and returns 15
-
Subtraction z = y - x; //performs subtraction and returns 5
*
z = x * y; //performs multiplication and returns 50
Multiplication
/ z = y / x; //performs division and returns 2
Division
% z = x % 2; //returns division remainder 1
Modulus
var x = 5;
++
Increment x++; //post-increment, x will be 5 here and 6 in the
next line
String Concatenation
var a = 5, b = "Hello ", c = "World!", d = 10;
Comparison Operators
Operator Example/Usage
var a = 5, b = 10, c = "5";
== var x = a;
equality
a == c; // returns true
===
equality with type a === c; // returns false
!=
a != b; // returns true
inequality
> a > b; // returns false
greater than
a < b; // returns true
<
less than a >= b; // returns false
Logical Operators
Operator Description
var a = 5, b = 10;
&&
AND Operator (a != b) && (a < b); // returns true
%=
Selection Structures
If-else Condition
JavaScript includes if-else conditional statements to control the program flow, similar to
other programming languages.
JavaScript includes following forms of if-else conditions:
1. if condition
2. if-else condition
3. else if condition
If Condition
Syntax
if(condition expression)
{
// code to be executed if condition is true
}
Example
If –else Condition
Syntax
Example
JavaScript includes loop structures like Java or C# that are used to execute code repeatedly.
JavaScript includes following forms of loops:
1. for loop
2. while loop
for loop
Syntax
Example
for (var i = 0; i < 5; i++)
{
console.log(i); // Output: 0 1 2 3 4
}
while loop
Syntax
while(condition expression)
{
/* code to be executed
till the specified condition is true */
}
Example
var i =0;
while(i < 5)
{
console.log(i); // Output: 0 1 2 3 4
i++;
}
for… of loop
Iterating
With the HTML Document Object Model (DOM), JavaScript can access and change all the
elements of an HTML document.
With the object model, we will be able to create a dynamic HTML page. Through JavaScript,
we can do the following:
1. Change all the HTML elements in the page;
2. Change all the HTML attributes in the page;
3. Change all the CSS styles in the page;
4. Remove existing HTML elements and attributes;
5. Add new HTML elements and attributes;
6. React to all existing HTML events in the page; and
7. Create new HTML events in the page.
The DOM is a programming interface that allows us to create, change, or remove elements
from the document.
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
When a web page is loaded, the browser creates a Document Object Model of the page.
The DOM views an HTML document as a tree of nodes and each node represents an HTML
element.
<html>
<head>
<title>My Title</title>
</head>
<body>
<h1>My header</h2>
<a href=””>My link</a>
</body>
</html>
As you may see in the illustrations above, our document is called the root node and contains
one child node which is the <html> element. The <html> element contains two children
which are the <head> and <body> elements. Both the <head> and <body> elements have
children of their own.
Selecting Elements in the Document
There are a few different methods for selecting an element in the HTML document.
getElementById()
querySelector()
querySelectorAll()
getElementById()
In HTML, ids are used as unique identifiers for the HTML elements. This means you cannot
have the same id name for two different elements. Hence, you easily target elements by its
id.
Hence, if you only want to select the first paragraph, you can do it like this.
const paragraph1 = document.getElementById("para1")
console.log(paragraph1);
The code above tells the computer to get the <p> element with the id of para1 and print the
element to the console.
To access the console, press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac)
<div class="page-content">
........
<p id="para1" class="card-body"> Hello! Tell us about yourself</p>
........
<p id="para2" class="card-body"> Tell us about your education</p>
........
<p id="para3" class="card-body"> Tell us about your IT Skills</p>
........
<p id="para4" class="card-body"> Share your IT projects</p>
.........
</div>
2. If everything is in order, add the JS script in the between the <script> tags.
const paragraph1 = document.getElementById("para1")
const paragraph2 = document.getElementById("para2")
console.log(paragraph1);
console.log(paragraph2);
3. Now, reload your page in the browser and access the console. You should be able
to see the html elements as selected.
In selecting elements in this query you don’t have to specify their Id. Instead you find
elements with one or more CSS selectors.
For example, if you have an HTML list of your favorite Netflix movies, you can use a
querySelector() to find one or more elements.
Such that you may do something like this if you want to target a single <h1> element.
Hence, you will get this output from the console.
Meanwhile, If I wanted to target the class="list" to print out the unordered list to the
console, then I would use .list inside the querySelector().
The . before list tells the computer to target a class name. If you wanted to target an id then
you would use a # symbol before the name.
This method finds all of the elements that match the CSS selector and returns a list of all of
those nodes.
So, based on the previous example on the list of Favorite Netflex TV shows, if I wanted to
find all of the <li> items on the list, you could use the > child combinator to find all of the
children of the <ul>.
That will give you the nodelist of all <li> items inside the <ul> element.
Please take note that selecting the elements are not your primary goal rather it is the only
the first step in order to make the content of your page dynamic. Once you have selected your
desired element you can apply varying CSS rulesets, animations or simply pulling the values
from the text nodes.
Let’s say you only have an <h1> element to your page as follows.
Now, you want to list down the upcoming movies you want to watch under the
<h1>element. So to do that, you can create a <ul> element using document.createElement()
method and assign it to a variable upcomingMoviesList.
let upcomingMoviesList = document.createElement("ul");
Then we need to add that <ul> element to the document using the appendChild() method.
document.body.appendChild(unorderedList);
The next part is to add a couple of <li> elements inside the <ul> element using
the createElement() method.
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange.
Uses of JSON
It is used while writing JavaScript based applications that includes browser
extensions and websites.
JSON format is used for serializing and transmitting structured data over network
connection.
It is primarily used to transmit data between a server and web applications.
Web services and APIs use JSON format to provide public data.
Many programming environments feature the ability to read (parse) and generate
JSON.
The JSON format is syntactically similar to the code for creating JavaScript objects. Because
of this, a JavaScript program can easily convert JSON data into JavaScript objects.
Since the format is text only, JSON data can easily be sent between computers, and used by
any programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
Type Details
Description
It is a double precision floating-point format in JavaScript and it depends on
implementation.
Number Syntax
Example
Description
It is a sequence of zero or more double quoted Unicode characters with
backslash escaping.
Syntax
String
Example
Description
It includes true or false values.
Syntax
Boolean
Example
Description
It is an ordered collection of values enclosed in square brackets [ ].
Array Syntax
Example
Object Description
Unordered sets of name/value pairs enclosed by curly braces {}.
Example
Null Description
Empty
Example
Exercise: Working with JSON file
1. Create an a students.json file that contains the following:
{
"students": [
{
"name": "Alice Johnson","age": 20,"course": "Information Technology"
},
{
"name": "Bob Smith","age": 22,"course": "Computer Science"
},
{
"name": "Vince Isaac","age": 19,"course": "Data Science"
}
]
}
3. In your index.html file, add the following element inside the page content <div>
as shown below.
<div class="page-content">
........
<h2>Student List</h2>
<ul id="student-list" class="card-body"></p>
</div>
4. If everything is in order, add the JS script in the between the <script> tags.
5. Now, reload your page in the browser and access the console. You should be able to
something like this.
🎯Objective: Enhance your portfolio by dynamically loading a JSON file that lists all the
subjects you have taken from 1st year to your current semester. The JSON file will be
hosted on your GitHub Page, and JavaScript will be used to fetch and display the data.
Step 1: Create Your JSON File as shown below and save as courses.json
{
"courses": [
{
"year_level": "1st",
"sem": "1st",
"code": "IT112",
"description": "Computer Programming 1",
"credit": "3.0"
},
{
"year_level": "1st",
"sem": "2nd",
"code": "IT113",
"description": "Computer Programming 2",
"credit": "3.0"
}
// Add all your courses here
]
}
🎯Objective: Enhance your portfolio by adding a search functionality that allows users to
search for a subject using keywords in the description. The search should filter the
displayed subjects dynamically based on user input.
Step 1: Modify HTML file to add a search bar above the course table:
Step 2: Modify Your JavaScript to Implement Search
Step 3: Improve CSS for the Search Bar
Step 4: Submit your URL for your JSON file and web portfolio with the new search
feature to your instructor.