0% found this document useful (0 votes)
6 views

Chapter 03-Client-Side Scripting Languages

Uploaded by

chennoufiselma31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 03-Client-Side Scripting Languages

Uploaded by

chennoufiselma31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

CHAPTER 3 CLIENT-SIDE SCRIPTING LANGUAGES


Content :
1.1. Introduction
1.2. Client-Side Scripting languages
1.3. Javascript Fundamantals
1.4. Document Object Model (DOM)
1.5. Accessing elements in an HTML document
1.6. Events and events handling
1.7. Form validation with JavaScript
1.8. Exercises

3.1. INTRODUCTION
This chapter provides an introduction to client-side scripting languages, with a focus on JavaScript. JavaScript is
the most common language used in effective client-side programming and it is the basic language that one has to
fully understand during this chapter. By the end of this chapter, students will have a solid understanding of
JavaScript programming concepts, data structures, libraries and the DOM (Document Object Model (DOM).

3.2. CLIENT-SIDE SCRIPTING LANGUAGES


As shown in Figure 3.1, client-side scripting languages are programming languages that run on the user's web
browser (client-side) rather than on the web server. These languages enable the creation of dynamic and interactive
elements within web pages.

Figure 3.1: The process of client-side scripting

The most popular client-side scripting languages are JavaScript, TypeScript (1995), VBScript (1996), JQuery
(2006) and PureScript (2013). These languages offer several advantages for web development including:
▪ Enhanced User Experience and making websites more engaging and user-friendly,
▪ Reduced Server Load by performing tasks on the client-side,
▪ Enable web pages to respond quickly to user actions without requiring a round trip to the server,
▪ Provide flexibility and ease of development
▪ Supported by all major web browsers, making them highly compatible across different platforms,
▪ They have a vast ecosystem with active communities, which means developers have access to abundant
resources, tutorials, forums, and libraries.

3.3. JAVASCRIPT FUNDAMENTALS


3.3.1. Presentation
JavaScript is a multipurpose programming language primarily used for creating interactive and dynamic content
on websites and web applications. It is a client-side scripting language that runs directly in a user's web browser.
JavaScript allows developers to enhance user experience by adding interactivity, animations, and real-time

1|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

updates to web pages without requiring constant communication with the server. Key features and characteristics
of JavaScript include:

▪ HTML Integration: JavaScript can be embedded directly within HTML code using <script> tags. It can
manipulate and modify the content and structure of a webpage.
▪ Event Handling: JavaScript can respond to user actions such as clicks, keyboard inputs, and mouse
movements, allowing developers to create interactive interfaces.
▪ Animations and Effects: JavaScript can be used to create animations, transitions, and effects that
enhance user experience by providing visual feedback.
▪ AJAX (Asynchronous JavaScript and XML): AJAX enables data to be fetched from the server in the
background without requiring a full page reload. This contributes to smoother and more responsive web
applications.
▪ Web APIs: Modern browsers provide various APIs (Application Programming Interfaces) that
JavaScript can access to perform tasks like manipulating the browser history, working with multimedia,
handling geolocation, and more.
▪ Libraries and Frameworks: JavaScript has a rich ecosystem of libraries and frameworks, such as
jQuery, React, Angular, and Vue.js, that provide pre-built components and tools for building complex
web applications more efficiently.
▪ Cross-Browser Compatibility: JavaScript is supported by all major web browsers, making it a reliable
choice for creating web content that works across different platforms.
▪ Server-Side JavaScript: While JavaScript is mainly used on the client side, it can also be used on the
server side with technologies like Node.js. This allows for building server-side applications using the
same language.

3.3.2. History of JavaScript


JavaScript, often abbreviated as JS, is one of the most influential programming languages
and plays a vital role in web development. It was created by Brendan Eich, a software
engineer at Netscape Communications Corporation, in 1995. Originally, it was known as
"Mocha" during its development phase, and then briefly named "LiveScript." Finally, it
was renamed "JavaScript" for marketing purposes to capitalize on the growing popularity
of Java at that time.
JavaScript made its first appearance in the Netscape Navigator 2.0 browser in September 1995. It was designed
as a simple, lightweight scripting language to add interactivity and dynamic elements to web pages.

Figure 3.2: Netscape Navigator 2.0 browser

2|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

To ensure that JavaScript could be implemented consistently across different browsers, Netscape submitted the
language to the European Computer Manufacturers Association (ECMA) for standardization. In 1997,
ECMAScript was established as the official standard for JavaScript. Since then, new versions of ECMAScript
have been released regularly, each introducing new features and improvements.
JavaScript's versatility and ability to run on the client-side (in web browsers) as well as the server-side (with
Node.js1) contributed to its rapid growth in popularity. Developers began using JavaScript for more complex
tasks, such as form validation and image sliders, making web pages more interactive and user-friendly.
As JavaScript gained traction, Microsoft developed its own implementation called "JScript" for Internet Explorer.
This led to a period known as the "Browser Wars" in the late 1990s and early 2000s, where different browsers
had their own versions of JavaScript with varying degrees of compatibility.
With the increasing complexity of web applications, developers sought ways to make the JavaScript code more
manageable and maintainable. This led to the emergence of popular JavaScript libraries and frameworks like
jQuery2, React3, and Vue.js4, which simplified web development and promoted best practices.
Today, JavaScript is not only limited to the browser but is also used on the server-side with Node.js, allowing
developers to create full-stack applications using a single language. It has become an integral part of the web
development landscape, driving innovation and shaping the modern web experience.
However, being executed on the client-side, JavaScript has some security considerations, such as preventing
cross-site scripting (XSS) attacks and ensuring the secure handling of user data.
The following example illustrates what you can do with JavaScript. It shows an example of a flashing grid of
coloured squares. In this example, a JavaScript function changes the colour of a randomly chosen square in the
grid every second. You can find the source code of this example is available in the exercises section.

Figure 3.3: A demonstration of JavaScript’s artful abilities (https://www.bookofjavascript.com/)

3.3.3. Link JavaScript code in HTML


JavaScript can be added to HTML file in two ways:

▪ Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the <script>
tag. The <script> tag can either be placed inside the <head> or the <body> tag according to the
requirement.

<script type="text/javascript">
alert ("This alert box was called with the onload event");
</script>

1
Node.js (https://nodejs.org/en) is an open-source server environment that allows you to run JavaScript on the server. It runs on various
platforms (Windows, Linux, Unix, Mac OS X, etc.).
2
JQuery (https://jquery.com/) is a fast, small, and feature-rich JavaScript library.
3
React (https://react.dev/), also known as React.js or ReactJS, is a free and open-source front-end JavaScript library for building user interfaces
based on components.
4
Vue.js (https://vuejs.org/) is an open-source model–view–view model front end JavaScript library for building user interfaces and single-
page applications. It provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be
they simple or complex.

3|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

▪ External JS: We can write JavaScript code in other files having an extension.js and then link this file
inside the <head> tag of the HTML file in which we want to add this code.

<script type="text/javascript" src="path-to-the-file.js" >


</script>

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, you can use several script tags.

3.3.4. JavaScript Variables


JavaScript defines two types of values:
▪ Fixed values also called Literals: The two most important syntax rules for fixed values are:
o Numbers are written with or without decimals (Examples: 10.50 or 1001).
o Strings are text, written within double or single quotes (Examples: "Ali 20" or 'Ali 20').
▪ Variable values also called variables. They are used to store data values. JavaScript automatically
declare variables, or use the keywords var, let and const.
o The var keyword was used in all JavaScript code from 1995 to 2015.
o The let and const keywords were added to JavaScript in 2015.
o The var keyword should only be used in code written for older browsers
The main differences between var, let and const are:
o const variables cannot be changed while let and var variables can be changed.
o var variables can be reassigned while let and const variables cannot.
o Variables defined with let cannot be redeclared.

x = 5; // automatically declared
y = 6; // automatically declared
z = x + y; // z stores the value 11
let w=y-x // w stores the value 1
let age=30; // age value can be changed
const pi = 3.14; // pi value cannot be changed
var r=pi*(x+y); // r stores 34.54 and this value can be changed

Note 1: It is considered good programming practice to always declare variables before use. Thus, it is better to
always declare variables. Only use var if you MUST support old browsers and use const if the value or the type
should not be changed (e.g., Arrays, function, object). let can be used if you cannot use const.
Note 02: It is also important to note that all JavaScript variables must be identified with unique names called
identifiers. They can be short names (like x and y) or more descriptive names (age, sum, total, etc.).
The general rules for constructing names for variables (unique identifiers) are:
1) Names can contain letters, digits, underscores, and dollar signs.
2) Names must begin with a letter and they can also begin with dollar ($) and underscore (_).
3) Names are case sensitive (y and Y are different variables).
4) Reserved words (like JavaScript keywords like @, #, %) cannot be used as names.
Note 03 (JavaScript comments): they can be used to explain JavaScript code, and to make it more readable.
They can also be used to prevent execution, when testing alternative code.
▪ Single Line Comments : Single line comments start with //. Any text between // and the end of the line
will be ignored by JavaScript (will not be executed).

4|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

▪ Multi-line Comments: Multi-line comments start with /* and end with */. Any text between /* and */
will be ignored by JavaScript.

/*
The code in this example:
Shows how you can use a
Single line comment and, a
Multi-line comment
*/
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2

3.3.5. JavaScript Operators


Operators are used to perform operations on variables and values. javascript divides the operators into the
following groups:
▪ Assignment Operators
▪ Arithmetic Operators
▪ Comparison (Relational) Operators
▪ Logical Operators
▪ Special Operators
Assignment operators (=) which assign values to JavaScript variables, as shown in the examples bellow.

let x = 10; // assign value 10 to x


let y=5; // assign value 5 to y
let x += y; //the same as x=x+y (x=15)
let x -= y; //the same as x=x-y (x=5)
let x *= y; //the same as x=x*y (x=50)
let x/= y; //the same as x=x/y (x=2)
let x %= y; //the same as x=x % y (x=0)
let x **= y; //the same as x=x**y (x=100)

Category Operator Description Example Result


Arithmetic Addition (+) Adds numbers let z = x + y; z=15
Operators Multiplication (*) Multiplies numbers let z = x * y; z=50
Subtraction Subtracts numbers let z = x - y; z=5
let x=10;
Division (/) Divides numbers let z = x / y; z=2
let y=5;
Modulus (%) Division Remainder let z = x / y; z=0
Increment (++x) Increments, then return value ++x; x=11
Increment (x++) Return value, then increments x ++; x=10
Decrement (--x) Decrements, then return value -- x; x=9
Decrement (--x) Return value, then decrements x--; x=10
Exponentiation (**) Raises the first operand to the power of the z = x**2; z=100
second operand.
Comparison == == (1==8) false
Operators != Not equal (1!=8) True
> Greater than (1>8) False
< Less than (1<8) True
>= Greater than or equal to (1>=8) false
<= Less than or equal to (1<=8) true
Logical Logical and (&&) Returns true if both statements are true 3>2 && 5<3 false
operators Logical or (||) Returns true if one of the statements is true 3>2 || 5<3 true
Logical not (!) Reverse the result, returns false if the 3! = 2 true
result is true
String (+) Concatenation (joint tow strings together) "33"+"14" "3314"

5|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

Note 01: In expressions that encompass several arithmetic operations, multiplication (*) and
division (/) have higher precedence than addition (+) and subtraction (-). When using
parentheses, the operations inside the parentheses are computed first. Thus, the precedence can
be changed by using parentheses.
Note 02: Comparison operators are used are used in logical statements to determine equality or difference
between variables or values. JavaScript has a Boolean data type. It can only take the values true or false
values. In javascript, you can use the Boolean () function to find out if an expression (or a variable) is true
or not (The Boolean value of 0 (zero) is false).
Note 03: Logical operators are used to determine the logic between variables: An expression containing
these operator returns either true or false depending upon whether expression results true or false.

3.3.6. JavaScript Data Types


JavaScript is a dynamically and loosely typed language, due to which we do not have to mention the type of a
variable at the time of the variable declaration, the JS engine will automatically determine the data type depending
upon the value assigned or reassigned to a variable.
In JavaScript, there are two main data types to hold or store different data of values.
1) Primitive: JavaScript primitive data types are data types that refer to a single value. They are built-in
data types and they can hold only a single value at a time. This includes:
o String: used to store or hold sequence characters enclosed in either single or double-quotes.
o Number: It represents any one integer, floating-point, or exponential value.
o Boolean: It returns either true or false.
o Undefined: A variable that is declared but not initialized with any value.
o Null: It represents a null value which means no value. A variable is initialized with null
2) Non-Primitive: JavaScript primitive data types are data types that refer to multiple values. It is used to
store or hold multiple values at a time. It includes:
o Arrays: It is used to store multiple elements.
o Objects: Elements which are stored as a key-value pair.
o Functions: It is a block of code enclosed in curly braces used to perform a specific task

Examples:
let name = "Rida"; //string
let age=32; //number
let b=4.55; //number
let c=10e3; //number
let x=false; //boolean
var a; //undefined
var b-null; //Null
let arr=[1,2,3]; //array
let obj={ name: "Rida", age:21}; //object
function fun() { // function
document.write("Hello")
}

6|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

In JavaScript, we can know the data type of a variable using the ‘typeof’ operator.

<!DOCTYPE html>
<html lan="en">
<head>
<meta charset="UTF-8">
<title>My Form</title>
</headf>
<body bgcolor="bisque">
<h1> Javascript Typeof </h1>
<script type="text/javascript">
let name = "Rida";
let age=32;
document.write(typeof(name)+ " ");
document.write(typeof(age))
</script>
</body>
</html>

3.3.7. JavaScript Output


JavaScript Output defines the ways to display the output of a given code. The output can be displayed by using
four different ways which are listed below:
Output function Description Example
It is used to access <p id="GFG"></p> <!--element P -->
innerHTML
an element. It <script> <!-- Script to use innerHTML -->
defines the HTML document.getElementById("GFG").innerHTML="Hello";
content. </script>
It is used for <script>
document.write()
testing purpose. let x=(3+5)/2;
document.write(x);
</script>
It displays the <script>
alert()
content using an alert("Result="+(10 * 2));
alert box </script>
It is used for <script>
console.log()
debugging let x=3+10;
purposes by console.log(x);
writing into the </script>
browser console
it allows to take <p id="GFG"></p> <!--element P -->
window.prompt
input from user <script> <!-- Script to use innerHTML -->
window.prompt("Please Enter your Input");
</script>

Example:
<!DOCTYPE html>
<html lan="en">
<head>
<meta charset="UTF-8">
<title>My Form</title>
</head>
<body bgcolor="bisque">
<h1> Javascript output </h1>
<script type="text/javascript">

7|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

// say Hello, world!


alert("Hello, world!");
</script>
</body>
</html>

3.3.8. Conditional Statements


Conditional statements are used to perform different actions based on different conditions. In JavaScript we have
the following conditional statements:

▪ Use if to specify a block of code to be executed, if a specified condition is true


▪ Use else to specify a block of code to be executed, if the same condition is false
▪ Use else if to specify a new condition to test, if the first condition is false
▪ Use switch to specify many alternative blocks of code to be executed

Examples

// Make a "Good day" greeting if the hour is less than 18:00:


if (hour < 18) {
greeting = "Good day";
}
//If the hour is less than 18, display "Good day", otherwise "Good evening":
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
/*If time is less than 10:00, display "Good morning", if not, but time is less
than 20:00, create a "Good day" greeting, otherwise a "Good evening":*/
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The switch statement is used to select one of many code blocks to be executed.
▪ The switch expression is evaluated once.
▪ The value of the expression is compared with the values of each case.
▪ If there is a match, the associated block of code is executed.
▪ If there is no match, the default code block is executed.

Break statement: when JavaScript reaches a break keyword, it breaks out of the switch block. This will stop
the execution inside the switch block. It is not necessary to break the last case in a switch block. The block breaks
(ends) there anyway. If you omit the break statement, the next case will be executed even if the evaluation does
not match the case.
The default keyword can be used to specify the code to run if there is no case match:
Example: This example uses the weekday number to calculate the weekday name. For that we use the predefined
javascript method getDay() of the instance Date(). This method returns the weekday as a number between 0
and 6 (Sunday=0, Monday=1, Tuesday=2 ..).

8|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

// Make a "Good day" greeting if the hour is less than 18:00:


let x= new Date().getDay();
switch (x) {
case 0: day = "Sunday"; break;
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday";

// If the x value is not in {0, 1, 2, 3, 4, 5,6}), write a default message:


default:
text = " Invalid day";
}
document.write("Today is"+ x);

3.3.9. Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the
code compact. It is mostly used in array. JavaScript supports different kinds of loops:
▪ for - loops through a block of code a number of times
▪ while - loops through a block of code while a specified condition is true
▪ do/while - also loops through a block of code while a specified condition is true

Examples
// increases i value each time the code block in the loop has been executed:
for (let i = 0; i < 5; i++) {
text = "The number is " + i + "<br>";
document.write(text);
}

// the same example with the while loop:


let i=0;
while (i < 5) {
text = "The number is " + i;
document.write(text);
i++;
}

// the same example with the do/while loop:


let i=0;
do {
text = "The number is " + i;
i++;
}
while (i < 5);

Results after running the code

9|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

3.3.10. Functions in Javascript


Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a
procedure, which is a set of statements that performs a task or calculates a value, but for a procedure to qualify
as a function, it should take some input and return an output where there is some obvious relationship between
the input and the output. It is executed only when "something" invokes it (calls it).
▪ With functions we can reuse code,
▪ we can write code that can be used many times, and
▪ we can use the same code with different arguments, to produce different results.
Syntax: A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses (). The parentheses may include parameter names separated by commas: (parameter1, parameter2,
...). The code to be executed, by the function, is placed inside curly brackets: {}.
When JavaScript reaches a return statement, the function will stop executing. Functions often compute a return
value. The return value is "returned" back to the "caller":
Examples: Function to compute and return the product of two numbers p1 and p2
// Function is called, the return value will end up in x (x=12)
let x = myFunction(4, 3);

// Function is used as a variable


document.write("the result is"+ myFunction(4, 3));

// Function declaration. It returns the product of p1 and p2


function myFunction(p1, p2) {
return p1 * p2;
}

As you can see in the example, functions can be used the same way as we use variables, in all types of formulas,
assignments, and calculations. So, instead of using a variable to store the return value of a function, you can use
the function directly, as a variable value.
Local Variables: Variables declared within a JavaScript function, become LOCAL to the function and can only
be accessed from within the function.
// Function is called, the return value will end up in x (x=12)
let x = max(20, 5);
document.write("the maximum is"+ x);
// Function declaration.
function max(num1, num2) {
let result; //result is a local variable to the function max
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

3.3.11. Objects in Javascript


Definition: Objects, in JavaScript, are the most important data type and form the building blocks for modern
JavaScript. An object is a collection of properties, and a property is an association between a name (or key) and
a value. A property's value can be a function, in which case the property is known as a method.
For example, a car is an object that has properties like weight and colour, and methods like start and stop. All
cars have the same properties, but the property values differ from car to car. Similarly, all cars have the same
methods, but the methods are performed at different times.

10 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

Object: car Properties Methods


car.name = Fiat car.start()
car.model = 500 car.drive()
car.weight = 850kg car.brake()
car.color = white car.stop()

Object Definition (declaration): Objects are variables too. But objects can contain many values. For example,
the code below assigns many values (Fiat, 500, white) to the object variable named car. It is a common practice
to declare objects with the const keyword.

// object declaration:
const car = {type:"Fiat", model:"500", colour:"white"};

Object Methods: Methods are actions that can be performed on objects and they are stored in properties as
function definitions. In the example below, the method fullName returns the full name of a person.

// Declaration of the object person


const person = {
firstName:"Karim",
lastName:"Ali",
age:50,
eyeColor:"blue"
fullName: function() { //method fullName
return this.firstName + " " + this.lastName;
}};

In the example above, the keyword this refers to the person object. So, “this.firstName” means the
“firstName” property of person and “this.lastName” means the “lastName” property of person.
Accessing object properties and methods: You can access object properties in two ways, as shown in the
example bellow. If you access a method without the () parentheses, it will return the function definition:

//You can access object properties in two ways:


person.lastName="Amir"; //or
person[lastName]="Amir";

//You access an object method with the following syntax:


var name = person.fullName(); //or
var name = person.fullName; // return the function definition

Note: when a JavaScript variable is declared with the keyword " new", the variable is created as an object, as
shown in the examples bellow. But it is better to avoid String, Number, and Boolean objects because they may
complicate your code and slow down execution speed.

x = new String(); // Declares x as a String object


y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object

Exercise: Create an array of objects, where each object describes a book and has properties for the title (a string),
author (a string), and alreadyRead (a boolean indicating if you read it yet). Then, iterate through the array of
books, and for each book, display the book title, book author and whether you read it yet or not.
Title author alreadyRead

'The Design of EveryDay Things' 'Don Norman' false


'The Most Human Human' 'Brian Christian', true

Solution:

11 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];

for (var i = 0; i < books.length; i++) {


var book = books[i];
var bookInfo = book.title + '" by ' + book.author;
if (book.alreadyRead) {
document.write('You already read "' + bookInfo +);
} else {
document.write('You still need to read "' + bookInfo);
}
}

3.3.12. Arrays
The Array object, as with arrays in other programming languages, enables storing a collection of multiple items
under a single variable name, and has members for performing common array operations. In JavaScript, arrays
aren't primitives but are instead Array objects with the following core characteristics:
▪ They are resizable and can contain a mix of different data types. (When those characteristics are
undesirable, use typed arrays instead.)
▪ They are not associative arrays and so, array elements cannot be accessed using arbitrary strings as
indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
▪ They are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on, and
the last element is at the value of the array's length property minus.
▪ Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
Examples of main operations in Javascript arrays:

// It is a common practice to declare arrays with the const keyword


const cars = ["Saab", "Volvo", "BMW"];
//we can also create an array, and then provide the elements:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
//The following example also creates an Array, and assigns values to it
const cars = new Array("Saab", "Volvo", "BMW");
//we access an array element by referring to the index number
let car = cars[0]; // cars=“Saab”
//This statement changes the value of the second element in cars
cars[1] = "Opel";
myArray[0] = Date.now; //we can have objects in an Array.
myArray[1] = myFunction; //we can have functions in an Array.
myArray[2] = cars; //we can have arrays in an Array:

Note: the full array can be accessed by referring to the array name. The JavaScript method toString() converts
an array to a string of (comma separated) array values.

12 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

<!DOCTYPE html> Result in the navigator


<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

const fruits = ["Banana", "Orange", "Apple"];


document.getElementById("demo").innerHTML =
fruits.toString();
</script>
</body></html>

Tow-Dimensional array: A two-dimensional array in Javascript can be thought of as an array of arrays. It can
be created using the new keyword or with nested array literals as shown in the example below:

//add the property “nationality” to the object person1


var array1= new Array(1,2,3);
var array2= new Array(2,3,4);
var array3= new Array(1,3,4);

var matrix1= new Array(array1, array2, array3); //2D array (constructors)


var matrix2= [[1,2,3], [2,3,4], [1,3,4]]; //2D array (nested array literals)

Array Properties and Methods: The real strength of JavaScript arrays are the built-in array properties and
methods. The table below present examples of the most important methods and properties of Javascript arraies.
Here are some examples of some array properties and methods.
1) The length property returns the length (size) of an array.
2) The method toString() converts an array to a string of (comma separated) array values.
3) The pop() method removes the last element from an array.
4) The push() method adds a new element to an array (at the end).
5) The shift() method removes the first array element and "shifts" all other elements to a lower index.
6) The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length; //Result size=4
document.write("Size= "+ size);
document.getElementById("demo").innerHTML = fruits.toString();
</script>

<p id="demo1"></p>
<p id="demo2"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits.pop();
document.getElementById("demo2").innerHTML = fruits;

13 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

let fruit = fruits.pop(); //returns the value that was "popped out":
</script>

<p id="demo3"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo3").innerHTML = fruits;
let length = fruits.push("Kiwi"); //length size=5
document.write("length= "+ lenght);
</script>

<p id="demo4"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo4").innerHTML = fruits;
let fruit = fruits.shift(); // Returns the value that was "shifted out":
document.write("fruit shifted out= "+ fruit);
</script>

<p id="demo5"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
document.getElementById("demo5").innerHTML = fruits;
fruits.unshift("Lemon"); // Result 5
</script>
</body></html>

3.3.13. Javascript Object Constructors


A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a
constructor gets called when an object is created using the new keyword. Their main purpose is to create a new
object and set values for any existing object properties.
When a constructor gets invoked in JavaScript, a new empty object gets created. The this keyword can be used
to refer to the new object and it becomes the current instance object. The new object is then returned as the return
value of the constructor.
Example: The example below shows the difference between constructor and Object Literal (studied in the
previous section). As you can see, an object literal is typically used to create a single object whereas a constructor
is useful for creating multiple objects.
In this example, we have created the Object class Person with the properties first name, last name, age and eye
colour. Thus, the constructor function Person() has 4 parameters that correspond to the object properties. It is
also considered good practice to name constructor functions with an upper-case first letter. In a constructor
function, the keyword this does not have a value. It is a substitute for the new object. The value of this will
become the new object when a new object is created.
In the example below, two objects person1 and person2 created by calling the constructor function with the new
keyword. In this case, arguments are passed to the constructor during object creation. This allows each object to
have different property values.

14 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

//Object literal (previous section)


var Person = {
FirstName: "Rida";
LastName: "Imed";
age: 25;
eyeColour = "Green";
}
//Constructor with 4 parameters
function User(FirstName, LastName, age, eyeColour) {
this.firstName = FirstName;
this.lastName = LastName;
this.age = age;
this.eyeColour= eyeColour;
}
//Two objects are created using the same constructor Person().
var person1 = new Person("Rida", "Imed", 25, "Green");
var person2 = new Person("Rima", "Ahmed", 32, "Blue");

1- Adding properties and methods to an object: In javascript, you can easily add new properties, or new
methods to an existing object, as shown in the examples below.
//add the property “nationality” to the object person1
person1.nationality = "Algerian";
//add the method name() to the object person1
person1.fullname = function () {
return this.firstName + " " + this.lastName;
};

▪ In the first example, the property “nationality” will be added only to the object person1. Not to
person2. (Not to any other Person () objects).

▪ In the second example, the method “fullname()” will be added only to the object person1. Not to
person2. (Not to any other Person () objects).
2- Adding properties and methods to a Constructor: You cannot add a new property, or a new method, to an
object constructor the same way you add a new property (method) to an existing object. As shown in the example
below, the new property, or method, must be added inside the constructor function.
//adding a new property (nationality) and a new method (fullName) to the
constructor Person()
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "Algerian";
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}

3- JavaScript Object Prototypes: All JavaScript objects inherit properties and methods from a prototype. In
this context, the Object.prototype is on the top of the prototype inheritance chain. Date objects, Array
objects, and Person objects inherit from Object.prototype.
The JavaScript prototype property allows you to add new properties to object constructors. It also allows you
to add new methods to objects constructors, as shown in the examples below.

15 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

// constructor Person()
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

// Add the property nationality to the constructor Person with prototype


Person.prototype.nationality = "Algerian";

// Add the method fullName to the constructor Person with prototype


Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};

Exercise: Write a JavaScript program to get the volume of a cylindrical with four decimal places using object
constrictors and the prototype property (volume=Cylindrical hight *PI*radios2).
<!DOCTYPE html>
<html>
<body>
<h1>Volume of a Cylinder</h1>

<script type="text/javascript">
//function constructor
function Cylinder(cyl_height, cyl_diameter) {
this.cyl_height = cyl_height;
this.cyl_diameter = cyl_diameter;
}
// Add the method Volume to the constructor Cylinder with prototype
Cylinder.prototype.Volume = function () {
var radius = this.cyl_diameter/2;
return this.cyl_height * Math.PI * radius * radius;
};
//create new object
var cyl = new Cylinder(7, 4);
// Volume of the cylinder with four decimal places.
alert('volume =', cyl.Volume().toFixed(4)); // volume =87.9646
</script>
</body></html>

Result after running the code:

4- Built-in JavaScript Constructors: In JavaScript, there are several built-in constructors that allow you to
create objects of various types. The examples below show the most important JavaScript built-in constructors for
native objects. Although these constructors exist, it is recommended to use primitive data types where possible,
because they may complicate your code and slow down execution speed.
// Built-in Constructors
var a = new Object();
var b = new String();
var c = new String('Ali') \\ similar to var c='Ali';
var d = new Number();
var e = new Number(25); \\ similar to var e=25;
var f = new Boolean();
var g = new Boolean(true); \\ similar to var g=true;

16 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

5- Date object: At times you there will be a need to access the current date and time and also past and future
date and times. In Javascript, we can create instances of the Date built-in object with the new keyword and the
Date’s constructors. Current date and time can be retrieved as shown below:
// Current date and time
var today =new Date();

After running the code, you get the full current date and time of your system as shown below.

Below are some of frequently used methods available on a Date object.


Method Description

toLocaleString A string of the date information


getDate The day of the month
getMonth The month of the year, as a number in the range of 0 to 11
getDay The day of the week, as a number in the range 0 to 6
getFullYear The year
getTime Number of milliseconds since Jan 1, 1970
getHours Number of the hours, as a number in the range 0 to 23
getMinutes Number of the minutes, as a number in the range 0 to 59
getSeconds Number of the seconds, as a number in the range 0 to 59
getMilliseconds Number of the Milliseconds, as a number in the range 0 to 999

Example: Write a JavaScript program to display the current date in the same format as below:

<!DOCTYPE html>
<html>
<body>
<h1>Volume of a Cylinder</h1>

<script type="text/javascript">
function myDate() {
weekdays = new Array ("Monday","Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday");
date_day = new Date();
d=weekdays[date_day.getDay()];

if (date_day.getDate()<10)
{n="0"+ date_day.getDate()}
else
{n=date_day.getDate()};
if (date_day.getMonth()+1<10)
{m="0"+ (date_day.getMonth()+1)}
else {m= date_day.getMonth()+1};
y= date_day.getFullYear();
today_date="Today date is "+d+" : "+n+" / "+m+" /" +y;
return(today_date);
}
var mydate = myDate();
window.document.writeln ("<br><center>"+"<h3><font color='purple'
size='5'>"+mydate+"</h3></center>");
</script>

17 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

</body></html>

3.4. DOCUMENT OBJECT MODEL (DOM)


When a web page is loaded, the browser creates a Document Object Model (DOM) of the page. DOM is an
Application Programming Interface (API) for web documents and a W3C (World Wide Web Consortium)
standard. It represents the structure of a document as a tree of objects, allowing programs to manipulate the
content, structure, and style of a web page dynamically. The top of the tree is the "document" node, which
corresponds to the entire web page. There are different types of nodes in the DOM, such as elements, attributes,
text, comments, etc.

Figure 3.4: Example of a DOM tree of objects


With the HTML DOM, JavaScript can access and change all the elements of an HTML document. This includes
adding, removing, or modifying elements (e.g., <div>, <p>, <span>) and their attributes (e.g., id, class, src). Thus,
using DOM along with javascript, we can create documents, navigate through the document structure, add or
delete elements and their content. In particular, with DOM, JavaScript gets all the power it needs to create dynamic
HTML:
▪ JavaScript can change all the HTML elements in the page
▪ JavaScript can change all the HTML attributes in the page
▪ JavaScript can change all the CSS styles in the page
▪ JavaScript can remove existing HTML elements and attributes
▪ JavaScript can add new HTML elements and attributes
▪ JavaScript can react to all existing HTML events in the page
▪ JavaScript can create new HTML events in the page

3.5. ACCESSING ELEMENTS IN AN HTML DOCUMENT


Different elements in the web are treated as objects in javascript and each object has properties and methods.
Using DOM, we can get the address of an HTML element in different ways.
1. By using the getElementById method
2. By using document object’s array property
3. By using the name attribute of the HTML elements
The first way and the most commonly used method is by using getElementById method. This method has been
introduced in DOM 1. Since the value for id attribute can be different for the same type of elements in a group,
there will be no problems.

18 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

In the second example, we use the innerHTML property of the getElementById method to change the content of
the <p> element with id="demo". The innerHTML property is very useful for getting or replacing the content of
HTML elements.
<!DOCTYPE html>
<html>
<body>
<h1>Accessing elements in an HTML document</h1>
<form action="post">
Enter your name: <input id="textid">
</form>
<p id="demo"></p>
<script type="text/javascript">
var name = document.getElementById("textid");
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body></html>

The second way is to use document object’s forms array property along with the element array property. For
example, you can use the script in the HTML code below for obtaining the address of the textbox in the form.
The main problem of this method is, it becomes difficult to obtain the address of elements when there are multiple
forms in a document or if there are a large number of elements in a form, or if new elements are added to a form.

<!DOCTYPE html>
<html>
<body>

<h1>Accessing elements in an HTML document</h1>


<form action="post">
Enter your name: <input type="text">
</form>
<script type="text/javascript">
Var name=document.form [0].elements[0].value;
</script>
</body></html>

The tired way is by using the name attribute of the HTML elements. The problem with this method is, it does not
work with a group of elements with the same name attribute like a group of checkboxes, or a group of radio
buttons which will have the same value for their name attribute in a form tag.

<!DOCTYPE html>
<html>
<body>

<h1>Accessing elements in an HTML document</h1>


<form action="post" name="formmain">
Enter your name: <input name="mytext">
</form>
<script type="text/javascript">
Var name=document.formmain.mytext.value;
</script>
</body></html>

19 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

3.6. EVENTS AND EVENTS HANDELING


The programming which allows computations based on the activities in a browser or by the activities performed
by the user on the elements in a document known as event-driven programming.
Events and Event Loop: An event is the specification (essentially an object created by the browser and
JavaScript) of something significant has occurred like click, submit, keyup, keypstroke, etc. In javascript, all the
event names are specified in lowercase. JavaScript uses an event loop to handle events. The event loop
continuously checks for events and executes associated code when an event occurs.
Event Handlers and Listeners: Event handlers are functions that are executed when a specific event occurs.
They are registered to specific events (like "click", "submit", "keyup", etc.) on DOM elements. Event listeners are
functions that "listen" for a specific type of event on a specific target (like a button or an input field). They are
attached to the target using methods like addEventListener.

// Get a reference to an element


const button = document.getElementById('myButton');
// Add an event listener
button.addEventListener('click', function() {
console.log('Button clicked!');
});

The table below lists most commonly used events and their associated tag attributes along with their corresponding
tags in HTML:
Event Tag Attribute Tag Description

change onchange <input> The input element is changed and loses focus
<textarea> The text area changes and loses focus
<select> The selection element is changed and loses focus
click onclick <a> The user clicks on the link
<input> The input element is clicked
Double click ondblclick Most elements The user double clicks the mouse left button
focus onfocus <a> The link acquires focus
<input> The input element acquires focus
<textarea> The text area acquires focus
<select> The selection element acquires focus
keydown onkeydown <body> A key is pressed down
Form elements
keypress onkeypress <body> A key is pressed down and released
Form elements
keyup onkeyup <body> A key is released
Form elements
load onload <body> The document finished loading
mousedown onmousedown Most elements The user clicks the left mouse button
mousemove onmousemonve Most elements The left mouse button is released
mouseover onmouseover Most elements The use moves the mouse cursor on the element
reset onreset <form> The reset button is clicked
select onselect <input> The mouse cursor is moved over the element
<textarea> The text is selected within the text area
submit onsubmit <form> The submit button is pressed
unload onunload <body> The user exists the document

Table 3.1: Most commonly used events


The process of linking an event handler with an event is known as registration. There are two ways to register an
event handler in DOM 0 event model.
▪ First way is by assigning the event handler script to an event tag attribute as shown below:

20 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

<input type="buton" value="Click Me" onclick="func1();"/>

In the above code, the event handler func1() is assigned to the event attribute onclick of the button tag
▪ The second way is by assigning the event handler to the event property of the element as shown below:

document.getElementById(ID-of-element).onclick=func1;

In the above code, the event handler func1() is assigned to the event attribute onclick of the button tag

3.7. FORM VALIDAION WITH JAVASCRIPT


One of the best uses of client-side scripting language JavaScript is the form input validation. The input given by
the user can be validated either on the client-side or on the server-side. By performing validation on the client-
side using JavaScript, the advantages are less load on the server, saving network bandwidth and quicker response
for the use.
Form input can be validated using different events, but the most common event used is submit, i.e., when the
submit button is clicked. Corresponding attribute to be used is onsubmit, as shown in the example below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Form</title>
<script type="text/javascript">
function checkData()
{
var txtuser = document.getElementById("txtuser").value;
var txtpass = document.getElementById("txtpass").value;
if (txtuser=="")
{
alert("Username must not be blank!");
return false;
}
if (txtpass=="")
{
alert("password must not be blank! ");
return false;
}
return true;
}
</script>
</head>

<body>
<form id="loginForm" action="next.html" onsubmit="checkData()">
Username: <input type="text" id="txtuser"><br/>
Password: <input type="pass" id="txtpass"><br/>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>
</body></html>

21 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

Explanation: The general validation process is to check whether the user input matches the requirements. If it
matches, return true which will make the browser shift the control to the page mentioned in the action attribute of
the form tag. Otherwise display appropriate error message and return false which will make the control stay in the
current page.

3.8. EXERCISES
Exercise 01: Write a JavaScript program that calculates the sum, difference, product, and quotient of two integer
numbers. Then, add this program to an HTML document that prompts the user for two numbers, calculates the
sum, difference, product, and quotient, and then displays the results.
Exercise 02: Input two numbers and perform arithmetic action using Select option as in the figure below.

Exercise 03: Write a JavaScript program that checks if an integer number is between 10 and 20 (inclusive) or if
it is greater than 100.
Exercise 04: Write a JavaScript program that compares two numbers and logs whether they are equal, not equal,
greater than, or less than.
Exercise 05: Write a JavaScript program that finds the maximum of three numbers.
Exercise 06: Write a JavaScript program that takes a student's numerical grade as input and outputs their
corresponding letter grade according to the following scale (The grade value is provided by the user.):
▪ A: 90-100
▪ B: 80-89
▪ C: 70-79
▪ D: 60-69
▪ F: Below 60.
Note: give two versions of the program, the first one is with the if… elseif statement and the second one is with
the switch statement.
Exercise 07: Write a JavaScript program that checks if a given character is a vowel or a consonant.

22 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

Exercise 08: Write a JavaScript program where the program takes a random integer between 1 and 10, and the
user is then prompted to input a guess number. The program displays a message "Good Work" if the input matches
the guess number otherwise "Not matched, Try another number".
Exercise 09: Write a JavaScript program to remove a character at the specified position in a given string and
return the modified string.
Exercise 10: Write a JavaScript program to test whether an array of length 2 does not contain 1 or 3.
Exercise 11: Write a JavaScript program to display the current day and time in the following format.
Today is: Tuesday. Current time is: 10 PM : 30 : 38
Exercise 12: Write a JavaScript program to find the longest string from a given array of strings.
Exercise 13: Write a function that calculates the area of a circle given its radius.
Exercise 14: Write a JavaScript function that accepts two arguments, a string and a letter and the function will
count the number of occurrences of the specified letter within the string.
Exercise 15: Write a JavaScript program that creates a class (constructor function) called 'Vehicle' with properties
for make, model, and year.
▪ Include a method to display vehicle details.
▪ Create a subclass called 'Car' that inherits from the 'Vehicle' class and includes an additional property for
the number of doors.
▪ Override the display method to include the number of doors.
Exercise 16: Write a JavaScript program that creates a class called 'Employee' with properties for name and
salary. Include a method to calculate annual salary.
▪ Create a subclass called 'Manager' that inherits from the 'Employee' class and adds an additional property
for department.
▪ Override the annual salary calculation method to include bonuses for managers.
▪ Create two instances of the 'Manager' class and calculate their annual salary.
Exercise 17: Write a JavaScript function that changes the background colour of a div element when the user
clicks on a button in the same HTML web page.
Exercise 18: Write a JavaScript program to create a slideshow that changes the displayed image when a next or
previous button is clicked.
Exercise 19: Lets the code HTML below.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Exercise-19</title>
<script type="text/javascript">
function couleur(parametre_couleur){
document.getElementById('dv').style.backgroundColor=parametre_couleur;
}
</script>
</head>
<body style="background-color:#FEF9E7">
<button onclick='couleur("blue")'> bleu </button>
<button onclick='couleur("green")'> vert </button>
<button onclick='couleur("red")'> rouge </button><br><br>
<div id='dv' style='height:500px;width:500px;background-color:black'></div><br>
</body></html>

1) What are “onclick” events used for?


2) Explain in few words what this program does.
3) Type it in an html editor, run it and in order to show the results.

23 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES

4) Change the event from “onclick” to “onmouseover” and rerun the code in order to see the results.
Exercise 20: Create the HTML form presented in the figure below, then use a CSS file to format it by using the
following properties.
▪ The body element has a font size of 10 points, a font family in {Verdana, Helvetica, sans-serif} and a
very dark lime green colour for the text (#003300).
▪ The header element (h1) has a font size of 10 points and it is centred.
▪ The paragraph has the following margins 0, 40, 20 and 40 pixels
▪ The td element padding is 5 pixels.
▪ The td elements of the labels are right aligned, while td elements for the form elements are left aligned

Create a JavaScript program that will be used to verify that the user has entered all of the required data and that
the data is valid. Your form validation script should verify the following:
▪ the e-mail has the '@' symbol,
▪ at least one period exists after the '@' symbol,
▪ the user has entered a valid month between 1 and 12 inclusive,
▪ the day does not exceed the allowable value for any month (Be sure to account for 29 days in February
on a leap year (use the LeapYear () function.),
▪ the user has entered a year between 1800 and 2999,
▪ the user has entered text for the city,
▪ the user has selected a state, i.e., not left the default blank,
▪ zip code is integer from 0 to 99999 (don't worry about 9-digit zip codes or ensuring that there are
exactly 5 digits),
Note: For each error, please use an alert () function to tell the user how to properly enter the incorrect value.

24 | P a g e

You might also like