1/14
Advanced Web Development
Prof. Moheb Ramzy Girgis
Department of Computer Science Faculty of Science
Minia University
6. JavaScript (I)
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
What Is A Scripting Language?
Scripting languages, also called script languages, are programming languages that are interpreted or compiled each time they run.
Scripts are executed directly from their source code, which are generally text files containing language specific
markup.
Thus, "scripts" are often treated as distinct from
"programs", which are typically compiled from source code into binary executable files only after they are
changed, and are then run from these binary files without needing the source code.
Scripts were created to shorten the traditional edit-compile-link-runprocess.
2/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
What Is JavaScript?
Despite the name, JavaScript and Javaare completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA (European Computer Manufacturer's Association) standard in 1997.
JavaScriptis a scripting language most often used for client-side web development.
JavaScriptis the default scripting language in all modern browsers, and in HTML5.
JavaScriptwas designed to add interactivity to HTML pages
A scripting language is a lightweight programming language
A JavaScriptconsists of lines of executable computer code
A JavaScriptis usually embedded directly into HTML pages
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
What can a JavaScript Do?
JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but
JavaScript is a scripting language with a very simple
syntax! Almost anyone can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
3/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
What can a JavaScript Do?
JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Example
"Hello World" Script
<script>
document.write("Hello World!")
</script>
The result of putting the script above into a page is:
Hello World!
<script> tag: tells the browser where the scripting starts (<script>) and ends (</script>).
document.writeis a standard JavaScript command for writing output to a page.
4/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
In HTML, JavaScript code must be inserted between
<script> and </script> tags.
JavaScripts in a page will be executed immediately while the page loads into the browser.
This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
Scripts in the head section
Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<html>
<head>
<script> .... </script>
</head>
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").
innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript Functions and Events
A JavaScriptfunction is a block of JavaScript code, that can be executed when
"called" for.
For example, a function can be called when
aneventoccurs, like when the user clicks a button.
Later, you will learn much more about functions and events.
5/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
Scripts in the body section
Scripts to be executed when the page loads go in the body section.
When you place a script in the body section it generates the content of the page.
<html>
<head>
<title>my First Script</TITLE>
</head>
<body>
<h1>Let’s Script...</h1>
<hr>
<script>
document.write("In this example a JavaScript is placed in the
<b> body section</b> of an HTML page.")
</script>
</body>
</html>
Note: Placing scripts at the bottom of the
<body> element improves the display speed, because script compilation slows down the display.
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
Scripts in both the body and the head section
You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the headsection.
<html>
<head>
<script>
....
</script>
</head>
<body>
<script>
....
</script>
</body>
6/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
Scripts Using an External JavaScript
Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js(e.g., myScript.js)
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag.
Example:
<script src="myScript.js"></script>
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.
Note: External scripts cannot contain <script> tags.
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
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:
Example:
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
7/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Where to Put the JavaScript
External References
External scripts can be referenced with a full URL or with a path relative to the current web page.
Examples:
1) use a full URL to link to a script
<script src="https://www.w3schools.com/js/myScript1.js"></script>
2) use a script located in a specified folder on the current web site:
<script src="/js/myScript1.js"></script>
3) link to a script located in the same folder as the current page:
<script src="myScript1.js"></script>
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The idattribute defines the HTML element.
The innerHTML property defines the HTML content
Example:
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
8/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Output
Using document.write()
It is a standard JavaScript command for writing output to a page.
Example:
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
Caution: Using document.write() after an HTML document is loaded, will delete all existing HTML.
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
The document.write() method should only be used for
testing.
Before Click After Click
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Output
Using window.alert()
You can use an alert box to display data
Example:
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
window.alert(“Hello”);
</script>
Using console.log()
For debugging purposes, you can use the console.log() method to display data
<script>
console.log(5 + 6);
</script>
Activate debugging in your browser with F12, and select
"Console" in the debugger menu
Later you will learn more about debugging.
9/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Statements
A computer program is a list of "instructions" to be
"executed" by a computer.
In a programming language, these programming instructions are called statements.
A JavaScript program, often called JavaScript code, is a list of programming statements.
The statements are executed, one by one, in the same order as they are written.
JavaScript statements are composed of: Values, Operators, Expressions,Keywords, and Comments.
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo”.
Add a semicolon at the end of each executable statement.
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Statements
Example:
<script>
var a, b, c;
a = 1;
b = 2;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b;
JavaScript White Space and Line Breaks
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
var person = "Hege";
var person="Hege";
In general, ending statements with a semicolonis optional!, but it is highly recommended.
10/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Statements
A good practice is to put spaces around operators (= + - * /)
var x = y + z;
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
document.getElementById("demo").innerHTML =
"Hello Dolly!";
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions, like this:
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Keywords
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
List of some of the keywords
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition return Exits a function
switch Marks a block of statements to be executed, depending on different cases try ... catch Implements error handling to a block of statements
var Declares a variable
11/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed, for example:
var x, y; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values are called literals.
Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
.
Strings are text, written within double or single quotes:
“John Doe” 'John Doe'
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
JavaScript Variables
In a programming language, variables are used to storedata values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
variables can be used in expressions.
Examples:
var x; // x is declared as a variable x = 6; // x is assigned (given) the value 6
var price1 = 5; // price1 is declared and assigned a value var price2 = 6; // price2 is declared and assigned a value
var total = price1 + price2; // price1 and price2 used in an expression
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiersshould be descriptive names, such as: age, sum, totalVolume).
12/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
Example:
<p id="demo"></p>
<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
varanswer = "The total price is: “;
document.getElementById("demo").innerHTML = answer + total;
</script>
JavaScript variables can hold numbers like 100 or strings like
"John Doe".
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description Addition
- Subtraction Multiplication Division
Modulus (Division Remainder) Increment
-- Decrement
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
JavaScript String Operators
The + operator and +=
assignment operator can be used to add (concatenate) strings.
Operator Example Same As x = y x = y += x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y /= x /= y x = x / y
%= x %= y x = x % y
var txt3 = txt1 + " " + txt2;
var txt1 = "What a very ";
txt1 += "nice day";
13/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will return a string:
var x = 5 + 5; // x will be 10
var y = "5" + 5; // y will be 55 var z = "Hello" + 5; // z will be Hello5
JavaScript
Comparison Operators
JavaScript Logical Operators
Operator Description
equal to
equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to ternary operator Operator Description
logical and logical or
logical not
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
JavaScript Operator Precedence
Operator Description
( ) Expression grouping
++, -- Postfix Increment and Decrement
++, -- Prefix Increment and Decrement
! Logical not
*, /, % Multiplication, Division, and Division Remainder
+, - Addition and Subtraction
<, <=, >, >=, ==,===, !=, !== Less than, Less than or equal, Greater than, Greater than or equal, Equal, Strict equal, Unequal, and Strict unequal
&& Logical AND
|| Logical OR
? : Condition
=, +=, -=, *=, /=, %= Assignment
14/14
Adv Web Development - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
JavaScript Syntax
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
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).
// This is a single line comment on a separate line
var x = 5; // a single line comment at the end of a line
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
/*
This is a Multi-line comment
*/