Java script
TBS/2019-2020
Introduction
2
JavaScript was designed to
To create interactive user interface in a web page (e.g., menu, pop-up
alert, windows, etc.)
Manipulating web content dynamically
Change the content and style of an element
Replace images on a page without page reload
Hide/Show contents
detect browsers,
create cookies,
etc.
It works in all major browsers.
Everyone can use JavaScript without purchasing a license.
Introduction
3
JavaScript is
NOT Java: the similarity in syntax is due to the C language.
a scripting language : lightweight programming language.
the most popular scripting language on the Internet.
an interpreted language : the scripts execute without
preliminary compilation.
executed on the client side: the browser.
usually embedded directly into web pages.
How to Insert Javascript? (1/3)
4
Javascripts can be added to HTML elements in 2
ways:
Internal javascript: Inside the HTML page
canbe placed in the <body>, or in the <head> section of an
HTML page, or in both.
External javascript: Outside the HTML page
in a separate javascript file (.js)
practical when the same code is used in many different web pages.
How to Insert Javascript? (2/3)
Internal: Inside the HTML page
5
page.html
Result
How to Insert Javascript? (3/3)
External: Outside the HTML page
6
page.html
script.js
Result
Remarks
7
<script type="text/javascript” >
The type attribute is NOT required. JavaScript is the default
scripting language in HTML.
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.
Javascript statements
8
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
A JavaScript program is a list of
programming statements.
In HTML, JavaScript programs are executed by the web
browser.
Ending Statements With a Semicolon?
9
With traditional programming languages, like C++ and
Java, each code statement has to end with a semicolon (;).
With javascript, ending statements with semicolon is not
required(optional), but highly recommended.
However, semicolons are required if you want to put more
than one statement on a single line.
JavaScript Variables (1/2)
10
Variables are used to store data.
A variable is a "container" for information you want to
store.
The value of a variable can change during the script.
You can refer to a variable by its identifier (name) to see its
value or to change it.
Rules for variable identifiers
Variable identifiers are case sensitive
Name, NAME and name refer to 3 different variables
They MUST begin with a letter or the underscore character
e.g.: name, _name
JavaScript Variables (2/2)
11
Declaration: with the keyword var
Example:
var x; // x is: undefined
x=10.0; // x is 10
x=“Hello“; // x contains the string “Hello”
var y =6; //y is 6
You do not need to specify the type of a variable at the declaration
var is used only once at the declaration
Remark:
Keywords are NOT case sensitive in javascript
e.g.: VAR , var and Var are the same keyword
JavaScript Operators (1/4)
12
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
Operators allow operation on
- Subtraction x=5 3
two or more values. y=2
JavaScript has two types of x-y
* Multiplication x=5 20
operators: arithmetic and
y=4
computation operators x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators (2/4)
13
Assignment Operators
Operator Example Is The Same As
The assignment expression (=) = x=y x=y
allows a variable to be
assigned a value. += x+=y x=x+y
Variables can be assigned any
value that matches their type -= x-=y x=x-y
and their description.
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators (3/4)
14
Comparison Operators Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for x=5
The comparison operator both value and
type) y="5"
returns a logical value of true
or false by comparing two or x==y returns true
more values with each other.
x===y returns
false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal 5>=8 returns false
to
<= is less than or equal to 5<=8 returns true
JavaScript Operators (4/4)
15
Logical Operators
Operator Description Example
&& and x=6
y=3
Binary operators combine
multiple comparison (x < 10 && y > 1)
returns true
operations into a single || or x=6
condition expression y=3
(x==5 || y==5)
returns false
! not x=6
y=3
!(x==y) returns
true
JavaScript Basic Examples
16
<script>
document.write("Hello World!")
</script>
TO DO: format the text with HTML code - heading
<script>
alert("Hello World!")
</script>
JavaScript Basic Examples
17
<script>
x=“Hello World!”
document.write(x)
</script>
<script>
x=“World”
document.write(“Hello” +x)
</script>
TO DO: add line breaks to separate the text in two lines
Remarks
18
The document.write() method should only be used for
testing.
Using document.write() after an HTML document is
loaded, will delete all existing HTML.
Example
<!DOCTYPE html>
<html>
<body>
<h1>Page Title here</h1>
<p>First paragraph here.</p>
<button type="button" onclick="document.write(5+6)">Try it</button>
</body>
</html>
Dialog Boxes
19
■ window.alert( )
message
Example:
window.alert("message"); OK
OK
Insert your name
cancel
■ window.prompt( )
Example:
var nom=window.prompt(“Insert your name:”);
■ window.confirm( ) Are you sure?
Example: OK cancel
var rep=window.confirm(“Are you sure?”);
JavaScript Popup Boxes (1/3)
20
Alert Box :
Syntax: window.alert(..) or alert(..)
An alert box is often used if you want to make sure information
comes through to the user.
When an alert box pops up, the user will have to click "OK" to
proceed.
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes (2/3)
21
Prompt Box
Syntax: window.prompt(..) or prompt(..)
A prompt box is often used if you want the user to input a
value before entering a page.
When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK“, the box returns the input value. If the
user clicks "Cancel“, the box returns null.
<script>
var name=prompt("What is your name? "," ")
document.write("Hello <br>"+name)
</script>
JavaScript Popup Boxes (3/3)
22
Confirm Box
Syntax: window.confirm(..) or confirm(..)
A confirm box is often used if you want the user to verify or
accept something.
When a confirm box pops up, the user will have to click either
"OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
var answer=confirm("Are you sure!")
Conditional Statements (1/3)
23
• Conditional statements are used to perform different
actions based on different conditions.
• if you want to execute some code only if a specified condition is true
if (condition)
{
code to be executed if condition is true
}
• if you want to execute some code if the condition is true and another
code if the condition is false
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements (2/3)
24
• Conditional statements are used to perform different
actions based on different conditions
if you want to select one of many blocks of code to be executed
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition1 is false and condition2 is true
}
else {
code to be executed if condition2 is false
}
Conditional Statements (3/3)
25
<script>
var x=prompt(" Enter a number ");
if(x<0)
{
alert ("You entered a negative number");
}
else
{
alert ("You entered a positive number");
}
</script>
JavaScript – When is it Executed?
26
JavaScript code is executed during the page loading or
when the browser fires an event
All statements are executed at page loading
Some statements just define functions that can be called later
Function calls or code can be attached as "event
handlers" via tag attributes
Executed when the event is fired by the browser
<img src="logo.gif" onclick="alert('clicked!')" />
Events
27
An event occurs as a result of some activity
A user clicks on a link in a page
Page finished loaded
Mouse cursor enter an area
A preset amount of time elapses
A form is being submitted
Calling a JavaScript Function from
Event Handler – Example
28
<html> image-onclick.html
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Document Object Model (DOM)
29
JavaScript arranges objects in a Document Object
Model or DOM.
The document object model can be thought of as a
hierarchy moving from the most general object to the most
specific.
window
frame event history document location navigator screen
document anchor form image link style tag
button checkbox input radio reset select submit textarea
Document Object Model (DOM)
30
Using the object model, the JS code manipulates
elements on an HTML page
we can examine elements' state
e.g. see whether a box is checked
we can change state
e.g. insert some new text into a div
we can change styles
e.g. make a paragraph red
DOM element objects
31
Accessing elements
32
Can be done in 3 ways:
document.getElementById(id) Finds an element by element id
Example
var myElement = document.getElementById("demo");
document.getElementsByTagName(name)Find elements by tag
name
Example
var x = document.getElementsByTagName("p");
document.getElementsByClassName(name)Find elements by class
name
Example
var x = document.getElementsByClassName("intro");
Changing HTML content
33
To change the content of an HTML element, use InnerHTML property
it sets or returns the HTML content (inner HTML) of an element.
Syntax
document.getElementById(id).innerHTML = new HTML
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">Old Heading</h1>
<script>
var element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Changing the Value of an Attribute
34
Syntax
document.getElementById(id).attribute = new value
Example
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src=”scenery.gif">
<script>
document.getElementById("myImage").src = "sunrise.jpg";
</script>
</body>
</html>
Changing HTML Style
35
Syntax
document.getElementById(id).style.property = new style
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello World!</p>
<script>
document.getElementById("demo").style.color = "blue";
</script>
<button type="button"
onclick="document.getElementById('demo').style.fontSize = '50px’ ">
click me</button>
</body>
</html>
Exercise 1
36
Change the background image of the web page created
on “lab1” depending on time of day
Use the following images
Day (http://eskipaper.com/images/sunny-day-background-1.jpg)
Night (http://images.all-free-
download.com/images/graphiclarge/traffic_at_night_184569.jpg)
Exercise 2
37
Create a web form containing three input fields as
follows
The user is asked to enter two integer values
The sum should be automaticaly displayed in the
third field
Exercise 3
38
Define a web form in which a user can specify if he
has kids or not using radio butons
If the user clicks on ‘yes’, a new text field in shown