Lecture 3: Java
Script(JS)
Web Engineering and Development
Dr. Mohamed Saied Amer
Introduction
Inthis lecture, we begin our introduction to the
JavaScript scripting language, which is used to enhance
the functionality and appearance of web pages.
JavaScript—is a de facto standard client-side scripting
language for web-based applications due to its highly
portable nature.
JavaScript serves two purposes:
1. It introduces client-side scripting, which makes web
pages more dynamic and interactive.
2. It provides the programming foundation for the
server-side scripting.
Main structure
JavaScript code will appear in the <head> section. Or may be
sometimes appear in <body> tag.
The browser interprets the contents of the <head> section first, so
the JavaScript programs execute before the <body> of the HTML5
document displays.
The script Element
<script> tag indicate that the text which follows is part of a script.
Example:
<script>
statements;
</script>
Webpage Objects
The browser creates a set of objects that allow you
to access and manipulate every element of an
HTML5 document.
document object: which represents the HTML5
document the browser is currently displaying.
Example: document.writeln();
window object: represents an open window in a
browser.
Example: window.alert();
First Script
We begin with a simple script (or program)
that displays the text "Welcome to
JavaScript Programming!" in the HTML5
1 document
<!DOCTYPE html>
2
3 <!-- Fig. 6.1: welcome.html -->
4 <!-- Displaying a line of text. -->
5 <html>
6 <head>
7 <meta charset = "utf-8">
8 <title>A First Program in JavaScript</title>
9 <script type = "text/javascript">
11 document.writeln(
12 "<h1>Welcome to JavaScript Programming!</h1>" );
14 </script>
15 </head><body></body>
16 </html>
Displaying Text in an Alert
Dialog
Sometimes it’s useful to display information in
windows called dialogs (or dialog boxes) that
“pop up” on the screen to grab the user’s attention.
Dialogstypically display important messages to
users browsing the web page.
The script in displays Welcome to JavaScript
Programming! As three lines in a predefined dialog
called an alert dialog.
9 <script type = "text/javascript">
10 <!--
11 window.alert( "Welcome to\
nJavaScript\nProgramming!" );
12 // -->
13 </script>
Obtaining User Input with prompt
Dialogs
A script can adapt the content based on input from the
user or other variables, such as the time of day or the
type of browser used by the client.
Such web pages are said to be dynamic, as opposed to
static, since their content has the ability to change.
Dynamic Welcome Page
Ournext script creates a dynamic welcome page that
obtains the user’s name, then displays it on the page.
Thescript uses another predefined dialog box from the
window object—a prompt dialog—which allows the user
to enter a value that the script can use.
Obtaining User Input with prompt
Dialogs
1 <!DOCTYPE html>
2
3 <!-- Fig. 6.5: welcome4.html -->
4 <!-- Prompt box used on a welcome screen -->
5 <html>
6 <head>
7 <meta charset = "utf-8">
8 <title>Using Prompt and Alert Boxes</title>
9 <script type = "text/javascript">
10 <!--
11 var name; // string entered by the user
12
13 // read the name from the prompt box as a string
14 name = window.prompt( "Please enter your name" );
15
16 document.writeln( "<h1>Hello " + name +
17 ", welcome to JavaScript programming!</h1>" );
18 // -->
19 </script>
20 </head><body></body>
21 </html>
Identifiers and Variables
Some valid identifiers:
Welcome
$value
_value
m_inputField1
button7
Some invalid identifiers:
7button (because it begins with a digit)
input field (because it contains a space)
Case Sensitivity
JavaScript is case sensitive—uppercase and lowercase letters are
considered to be different characters, so name, Name and NAME are
different identifiers.
Comments in JavaScript
There are two types of comments:
a single-line comment that begins with the
characters // states the purpose of the variable in
the script.
write multiline
/* This comments. For example,
is a multiline
comment. It can be
split over many lines.
*/
is a multiline comment spread over several lines.
Datatypes in JavaScript
JavaScript
does not require variables to have a declared
type before they can be used in a script.
A variable in JavaScript can contain a value of any data
type, and in many situations, JavaScript automatically
converts between values of different types for you.
For
this reason, JavaScript is referred to as a loosely
typed language.
When a variable is declared in JavaScript, but is not
given a value, the variable has an undefined value.
Datatypes in JavaScript
String, Number, Bigint, Boolean, Symbol, Object
Examples:
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular
task.
A JavaScript function is executed when "something" invokes it (calls it).
Example:
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
Function Return
Example:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
JavaScript Objects
Objects are variables too. But objects can contain many
values.
This code assigns many values (Fiat, 500, white) to
an object named car:
Example:
const car = {type:"Fiat", model:"500", color:"white"};
Object properties can be changed, added, deleted, and
some are read only.
JavaScript Strings
A JavaScript string is zero or more characters written inside
quotes.
String Length:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Escape Characters:
Because strings must be written within quotes, JavaScript Result
Code will
misunderstand this string. \b Backspace
\f Form Feed
Example:
\n New Line
let text = "We are the so-called "Vikings" from the north.";
\r Carriage Return
We use escape characters to fix this.
\t Horizontal Tabulator
let text = "We are the so-called \"Vikings\" from the north.";
\v Vertical Tabulator
JavaScript String Methods
All string methods produce a new string without altering the original string.
charAt()
The charAt() method returns the character at a specified index (position) in
a string:
Example:
let text = "HELLO WORLD";
let char = text.charAt(0); // will contains ‘H’
slice()
extracts a part of a string and returns the extracted part in a new string.
Example:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); // will contains ‘Banana’
JavaScript String Methods
A string is converted to upper case with
toUpperCase().
A string is converted to lower case with
toLowerCase().
joins two or more strings with concat() .
The trim() method removes whitespace from both
sides of a string.
JavaScript if, else, and else if
Conditional statements are used to perform different actions based
on different conditions.
Example:
if (condition) {
// block of code to be executed if the condition is true
}
Use the else statement to specify a block of code to be executed if
the condition is false.
Example:
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
JavaScript For Loop
Loops can execute a block of code a number of
times.
Example:
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
JavaScript While Loop
Loops can execute a block of code as long as a specified condition is
true.
Example:
while (condition) {
// code block to be executed
}
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat.
Example:
do {
text += "The number is " + i;
i++;
}
Javascript Events
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
Examples:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Javascript Events Example
<head>
<script>
function displayDate(){
document.writeln(“Welcome”);
}
</script>
</head>
<body>
<button onclick="displayDate()">The time is?</button>
</body>
Thanks
Any questions?