0% found this document useful (0 votes)
12 views30 pages

Module 4 - JavaScript

Module 4 focuses on making websites interactive through JavaScript, a scripting language that enhances web pages with dynamic content and multimedia control. It covers the basics of JavaScript, including its history, embedding methods, variable declaration, data types, operators, and control structures like loops and conditionals. The module emphasizes the importance of JavaScript in creating engaging web experiences and provides practical exercises for embedding and using JavaScript effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views30 pages

Module 4 - JavaScript

Module 4 focuses on making websites interactive through JavaScript, a scripting language that enhances web pages with dynamic content and multimedia control. It covers the basics of JavaScript, including its history, embedding methods, variable declaration, data types, operators, and control structures like loops and conditionals. The module emphasizes the importance of JavaScript in creating engaging web experiences and provides practical exercises for embedding and using JavaScript effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

Module 4

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.

Make no mistake, aesthetic design is an important element in every website. However,


putting life and meaning to your website adds that layer of excitement that make your
visitors want for more.

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?

JavaScript is a scripting language that enables you to create


dynamically updating content, control multimedia, animate
images, and pretty much everything else. It was created in May
1995 in 10 days, by Brendan Eich. Eich worked at Netscape and
implemented JavaScript for their web browser, Netscape
Navigator.

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:

Linking the external script

<script src="myScript.js"></script>

Warning: External scripts cannot contain <script> tags.

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.

External JavaScript Advantages

Placing scripts in external files has some advantages:


 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

To add several script files to one page - use several script tags:

<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

External References

An external script can be referenced in 3 different ways:


 With a full URL (a full web address)
 With a file path (like /js/)
 Without any path
The following are examples of the three ways:

<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.

Exercise: Embedding JavaScript

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>

2. Insert the code in between the script tags.

<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.

alert("This is an alert box."); // display string message

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;

if (confirm("Do you want to save changes?") == true)


{
choice = "Data saved successfully!";
} else {
choice = "Save Cancelled!";
}

Prompt Box

Syntax

prompt([string message], [string defaultValue]);

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.

var tenure = prompt("Please enter your age", "18");

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.

Use the reserved keyword var to declare a variable in JavaScript.


Syntax

var <variable-name>;
var <variable-name> = <value>;

Examples

var status; // declaring a variable without assigning a value


var status = ON; // declaring a variable with assigned value

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.

var greet = "Hello " // global variable

function myfunction(){
var name = "Vince!";
alert(greet + name); //can access global and local
variable
}

myfunction();

alert(greet);//can access global variable


alert(name); //error: can't access local variable
Rules in naming Variables

 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.

Data Types in JavaScript

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

var str = 'Hello World';

str[0] // H
str[1] // e
str[2] // l
String
str[3] // l
str[4] // o

str.length // 11

var num1 = 100; // integer


var num2 = -100; //negative integer

var num3 = 10.52; // float


var num4 = -10.52; //negative float
Numbers
var num5 = 0xfff; // hexadecimal
var num6 = 256e-5; // exponential
var num7 = 030; // octal
var num8 = 0b0010001; // binary
var YES = true;
var NO = false;

if(YES){
alert("This code block will be executed");
Boolean }

if(NO){
alert("This code block will not be executed");
}

var p1 = { name:"Vince" }; // object literal syntax

Object var p2 = new Object(); // Object() constructor


function
p2.name = "Vince"; // property
Date(); //Returns current date and time string
//or
var currentDate = new Date(); //returns date object
of current date and time
Date
//Date() Formats
date.toDateString(); 'Tue Feb 10 2015'
date.toLocaleDateString(); '2/10/2015'
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
Array var decimalArray = [1.1, 1.2, 1.3];
var booleanArray = [true, false, false, true];
var mixedArray = [1, "two", "three", 4];
var myVar = null;
alert(myVar); // null
Null &
Undefined var myVar;
alert(myVar); // undefined
Operators in JavaScript

JavaScript includes operators same as other languages. An operator performs some


operation on single or multiple operands (data value) and produces a result. For example,
in 1 + 2, the + sign is an operator and 1 is left side operand and 2 is right side operand.
The + operator performs the addition of two numeric values and returns a result.

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

++x; //pre-increment, x will be 7 here

-- x--; //post-decrement, x will be 7 here and 6 in the


next line
Decrement
--x; //pre-decrement, x will be 5 here

String Concatenation
var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; //returns "5Hello "


+ Operator with
b + c; //returns "Hello World!"
String
a + d; //returns 15

b + true; //returns "Hello true"


c - b; //returns NaN; - operator can only be used
with numbers

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

>= a <= b; // returns true


greater than or equal
<=
less than or equal

Logical Operators
Operator Description
var a = 5, b = 10;
&&
AND Operator (a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false


|| (a < b) || (a == b); // returns true
OR Operator
!(a < b); // returns false

! !(a > b); // returns true


NOT Operator
Assignment Operators
Operator Example/Usage
var x = 5, y = 10, z = 15;
=
x = y; //x would be 10 (assigns value)

+= x += 1; //x would be 6 (sums up value)

x -= 1; //x would be 4 (subtracts value)


-=
x *= 5; //x would be 25 (multiplies value)
*= x /= 5; //x would be 1 (divides value)

x %= 2; //x would be 1 (gets the modulus)


/=

%=

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

var myHeight = 1000;


var yourHeight = 500;

if(myHeight > yourHeight)


{
alert("I am taller than you.");
}

If –else Condition

Syntax

Example

var myHeight = 1000;


var yourHeight = 500;

if( myHeight > yourHeight)


{
alert("I am taller than you.");
}else
{
alert("You are taller than me.");
}
Looping Structures

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

for(initializer; condition; iteration)


{
// Code to be executed
}

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

The for... of statement loops through the elements of an iterable object.

for (variable of iterable) {


// code block to be executed
}

Iterating

Iterating simply means looping over a sequence of elements.


Here are some easy examples:
 Iterating over a String
 Iterating over an Array
 Iterating over a Map

Iteration Over a String

const name = "VinceIsaac";

for (const x of name) {


// code block to be executed
}

Iteration Over an Array

const letters = ["a","b","c"];

for (const x of letters) {


// code block to be executed
}
Iteration Over a Map
const fruits = new Map([
["pineapple", 1000],
["melon", 800],
["dragon fruit", 600]
]);

for (const x of fruits) {


// code block to be executed
}
(A Map holds key-value pairs where the keys can be any datatype.)

JavaScript HTML DOM

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.

What is the DOM?

The DOM is a programming interface that allows us to create, change, or remove elements
from the document.

Based on the W3C DOM standard, it is separated into 3 different parts:


 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
What is the HTML DOM?

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.

The HTML DOM (Document Object Model)

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.

For example, you have <p> elements in your document as follows.


<p id="para1"> This is the first paragraph. </p>
<p id="para2"> This is the second paragraph. </p>

You can select them individually by their id using this syntax.


document.getElementById("id name")

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)

Exercise: Selecting HTML elements


1. In your index.html file, make sure that you have the following <p> elements are
present as you have added in the previous modules.

<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.

The querySelector() function

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.

<h1>Favorite Netflix TV shows</h1>


<ul class="list">
const elementH1 = document.querySelector("h1");
<li>Money Heist</li>
console.log(elementH1);
<li>Bridgerton</li>
<li>Extraordinary Attorney Woo</li>
<li>Peaky Blinders</li>
</ul>

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().

const list = document.querySelector(".list");


console.log(list);

Consequently, you will get this output.

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.

The querySelectorAll() function

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>.

const listItems = document.querySelectorAll("ul > li");


console.log(listItems);

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.

Adding New Elements in the Document


Aside from just selecting the elements you can also add new elements to the DOM tree.

Let’s say you only have an <h1> element to your page as follows.

<h1>Upcoming movies I want to watch:</h1>

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.

let listItem1 = document.createElement("li");


let listItem2 = document.createElement("li");

JavaScript Object Notation (JSON)

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange.

 The format was specified by Douglas Crockford.


 It was designed for human-readable data interchange.
 It has been extended from the JavaScript scripting language.
 The filename extension is .json.
 JSON Internet Media type is application/json.
 The Uniform Type Identifier is public.json.

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.

Why use 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()

The JSON Syntax


Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a
subset of JavaScript syntax; it includes the following:
 Data is represented in name/value pairs.
 Curly braces hold objects and each name is followed by ':'(colon), the name/value
pairs are separated by , (comma).
 Square brackets hold arrays and values are separated by ,(comma)
Below is a simple example:

Notice how data


are organized in
hierarchical { } for
an object
Items are separated
by comma

All items are in


name:value pairs. We
use { } for a complex
value type, such as the
“book” value

Names are always


enclosed by " "

JSON supports the following two data structures:


 Collection of name/value pairs: This Data Structure is supported by different
programming languages.
 Ordered list of values: It includes array, list, vector or sequence etc.

Recommended viewer, converter, validator : https://jsonformatter.org/


JSON Data types

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"
}
]
}

2. Upload the students.json file to your github pages repository (xxxx.github.io).

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.

📌 Assessment Task: Adding "Subjects Taken" to Your Portfolio

🎯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
]
}

Step 2: Upload courses.json to your GitHub page repository.


Step 3: Modify Your HTML and CSS files accordingly to accommodate your courses that
you will show your portfolio
Step 4: Add JavaScript to Fetch JSON in your portfolio
Step 5: Submit your URL for your JSON file and web portfolio to your instructor.
📌 Skills Challenge: Adding a Search Feature

🎯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.

You might also like