Web Technologies
JavaScript
Muhammad Kamran
Week 7
Introduction to
JavaScript
Muhammad
Kamran
Table of Contents (2)
Introduction to JavaScript
What is JavaScript
Implementing JavaScript into Web
pages
In <head> part
In <body> part
In external .js file
3
Table of Contents (3)
JavaScript Syntax
JavaScript operators
JavaScript Data Types
JavaScript Pop-up boxes
alert, confirm and prompt
Conditional and switch statements,
loops and functions
Document Object Model
Debugging in JavaScript
4
What is DHTML?
Dynamic HTML (DHTML)
Makes possible a Web page to react
and change in response to the
user’s actions
DHTML = HTML + CSS + JavaScript
DHTML
XHTM JavaScri
CSS DOM
L pt
5
JavaScript
JavaScript is a front-end scripting
language developed by Netscape
for dynamic content
Originally called LiveScript
Lightweight, but with limited
capabilities
Can be used as object-oriented
language
A client-side scripting language
Client-side refers to the fact that it is
executed in the client (software) that 6
JavaScript
Client-side technology
Embedded in your HTML page
Interpreted by the Web browser
Interpreted on-the-fly by the client
Each line is processed as it loads in
the browser
Simple and flexible
Powerful to manipulate the DOM
7
Client Side Scripting
8
JavaScript Advantages
JavaScript allows interactivity such
as:
Implementing form validation
React to user actions, e.g. handle
keys
Changing an image on moving
mouse over it
Sections of a page appearing and
disappearing
Content loading and changing
dynamically 9
The First Script
first-
[Link]
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
10
Another Small Example
small-
[Link]
<html>
<body>
<script type="text/javascript">
[Link]('JavaScript rulez!');
</script>
</body>
</html>
11
Using JavaScript Code
The JavaScript code can be placed
in:
<script> tag in the head
<script> tag in the body – not
recommended
External files, linked via <script>
<script src="[Link]"
tag the head
type="text/javscript">
<!– code placed here will not be executed! --
>Files usually have .js extension
</script>
12
JavaScript – When is
Executed?
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
<img src="[Link]"
tag attributes
onclick="alert('clicked!')" />
Executed when the event is fired by 13
Calling a JavaScript
Function from Event
Handler – Example
<html> image-
<head> [Link]
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="[Link]"
onclick="test('clicked!')" />
</body>
</html>
14
Using External Script
Files
Using external script files:
<html> external-
<head>
[Link]
<script src="[Link]" type="text/javascript">
</script>
</head> The <script> tag is
<body> always empty.
<button onclick="sample()" value="Call
JavaScript
function from [Link]" />
</body>
</html>
External JavaScript file:
function sample() {
alert('Hello from [Link]!')
} sample.j
s 15
The
JavaScript
Syntax
JavaScript Syntax
The JavaScript syntax is similar to
C# and Java
Operators (+, *, =, !=, &&, ++, …)
Variables (typeless)
Conditional statements (if, else)
Loops (for, while)
Arrays (my_array[]) and associative
arrays (my_array['abc'])
Functions (can return value)
Function variables (like the C# 17
Data Types
JavaScript data types:
Numbers (integer, floating-point)
Boolean (true / false)
String type – string of characters
var myName = "You can use both single or
double quotes for strings";
Arrays
var my_array = [1, 5.3, "aaa"];
Associative arrays (hash tables)
var my_hash = {a:2, b:3, c:"text"};
var arr = { "one": 1, "two": 2, "three": 3 }; 20
Everything is Object
Every variable can be considered
as object
For example strings and arrays have
[Link]
member functions:
var test = "some string";
alert(test[7]); // shows letter 'r'
alert([Link](5)); // shows letter
's'
alert("test".charAt(1)); //shows letter
'e'
alert("test".substring(1,3));
var arr = [1,3,4]; //shows
'es'
alert ([Link]); // shows 3
[Link](7); // appends 7 to end of
array
alert (arr[3]); // shows 7
23
String Operations
The + operator joins strings
string1 = "fat ";
string2 = "cats";
alert(string1 + string2); // fat cats
What is "9" + 9?
alert("9" + 9); // 99
Converting string to number:
alert(parseInt("9") + 9); // 18
24
Arrays Operations and
Properties
Declaring new empty array:
var arr = new Array();
Declaring an array holding few
elements:
var arr = [1, 2, 3, 4, 5];
Appending
[Link](3); an element / getting the
var element = [Link]();
last element:
[Link];
Reading the number of elements
(array length):
[Link](1);
25
Standard Popup Boxes
Alert box with text and [OK] button
Just a message shown in a dialog
box:
alert("Some text here");
Confirmation box
Contains
confirm("Aretext, [OK] button and
you sure?");
[Cancel] button:
Prompt box
prompt ("enter amount", 10);
Contains text, input field with 26
27
JavaScript Prompt –
Example
[Link]
ml
price = prompt("Enter the price",
"10.00");
alert('Price + VAT = ' + price * 1.2);
28
Conditional Statement
(if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
Symb Meaning
ol
> Greater than
< Less than
>= Greater than or
equal to
<= Less than or equal
to
== Equal
!= Not equal
29
Conditional Statement
(if) (2)
The condition may be of Boolean or
integer type:
[Link]
var a = 0;
var b = true;
if (typeof(a)=="undefined" ||
typeof(b)=="undefined") {
[Link]("Variable a or b is undefined.");
}
else if (!a && b) {
[Link]("a==0; b==true;");
} else {
[Link]("a==" + a + "; b==" + b + ";");
}
30
Loops
Like in C#
for loop
while loop
do … while loop
var counter;
for (counter=0; counter<4; counter++) {
alert(counter);
}
while (counter < 5) {
alert(++counter);
} [Link]
31
Functions
Code structure – splitting code into
parts
Data comes in, processed, result
returned Parameters
function average(a, b, come in here.
c)
{ Declaring
var total; variables is
total = a+b+c; optional.
return total/3;
Type is never
}
declared.
Value
returned here.
32
Function
Arguments
and Return Value
Functions are not required to
return a value
When calling function it is not
obligatory to specify all of its
arguments
The function has access to all the
function sum() {
arguments
var sum = 0; passed via arguments array
for (var i = 0; i < [Link]; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); [Link]
33
Sum of Numbers –
Example
sum-of-
[Link]
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt([Link]);
value2 =
parseInt([Link]);
sum = value1 + value2;
[Link] = sum;
}
</script>
34
</head>
Sum of Numbers –
Example (2)
[Link]
(cont.)
<body>
<form name="mainForm">
<input type="text" name="textBox1" />
<br/>
<input type="text" name="textBox2" />
<br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
35
Document
Object Model
(DOM)
Document Object Model
(DOM)
Every HTML element is accessible via
the JavaScript DOM API
Most DOM objects can be
manipulated by the programmer
The event model lets a document to
react when the user does something
on the page
Advantages
Create interactive pages
Updates the objects of a page without 37
Accessing Elements
Access elements via their ID
attribute
var elem = [Link]("some_id")
Via the= name attribute
var arr
[Link]("some_name")
Via tag name
var imgTags = [Link]("img")
Returns array of descendant <img>
elements of the element "el"
38
DOM Manipulation
Once we access an element, we can
read and write its attributes
[Link]
function change(state) {
var lampImg =
[Link]("lamp");
[Link] = "lamp_" + state + ".png";
var statusDiv =
[Link]("statusDiv");
[Link] = "The lamp is " +
state";
}
…
<img src="test_on.gif"
39
Common Element
Properties
Most of the properties are derived
from the HTML attributes of the
tag
E.g. id, name, href, alt, title, src,
etc…
style property – allows modifying
the CSS styles of the element
Corresponds to the inline style of
the element
Not the properties derived from
embedded or external CSS rules 40
Common Element
Properties (2)
className – the class attribute of
the tag
innerHTML – holds all the entire
HTML code inside the element
Read-only properties with
information for the current
element and its state
tagName, offsetWidth, offsetHeight,
scrollHeight, scrollTop, nodeType,
etc…
41
Accessing Elements
through the DOM Tree
Structure
We can access elements in the
DOM through some tree
manipulation properties:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
42
Accessing Elements
through the DOM Tree –
Example
var el = [Link]('div_tag');
alert ([Link][0].value);
alert ([Link][1].
getElementsByTagName('span').id);
…
<div id="div_tag">
<input type="text" value="test text" />
<div>
<span id="test">test span</span>
</div>
</div> accessing-elements-
[Link]
Warning: may not return what you
expected due to Browser
43
The HTML
DOM Event
Model
The HTML DOM Event
Model
JavaScript can register event
handlers
Events are fired by the Browser and
are sent to the specified JavaScript
event handler function
<img src="[Link]"
Can be set with HTML
onclick="imageClicked()" /> attributes:
var img =
Can be accessed through the DOM:
[Link]("myImage");
[Link] = imageClicked;
45
The HTML DOM Event
Model (2)
All event handlers receive one
parameter
It brings information about the
event
Contains the type of the event
(mouse click, key press, etc.)
Data about the location where the
event has been fired (e.g. mouse
coordinates)
Holds a reference to the event
sender 46
The HTML DOM Event
Model (3)
Holds information about the state
of [Alt], [Ctrl] and [Shift] keys
Some browsers do not send this
object, but place it in the
[Link]
Some of the names of the event’s
object properties are browser-
specific
47
Common DOM Events
Mouse events:
onclick, onmousedown, onmouseup
onmouseover, onmouseout,
onmousemove
Key events:
onkeypress, onkeydown, onkeyup
Only for input fields
Interface events:
onblur, onfocus
onscroll 48
Common DOM Events
(2)
Form events
onchange – for input fields
onsubmit
Allows you to cancel a form
submission
Useful for form validation
Miscellaneous events
onload, onunload
Allowed only for the <body> element
Fires when all content on the page
49
onload Event – Example
onload event [Link]
<html> ml
<head>
<script type="text/javascript">
function greet() {
alert("Loaded.");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
50
The Built-In
Browser
Objects
Built-in Browser
Objects
The browser provides some read-
only data via:
window
The top node of the DOM tree
Represents the browser's window
document
holds information the current loaded
document
screen
Holds the user’s display properties
browser 52
DOM Hierarchy –
Example
window
navigato screen documen history location
r t
form form
butto form
n
53
Opening New Window –
Example
[Link]()
window-
var newWindow = [Link]("", [Link]
"sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");
[Link](
"<html><head><title>
Sample Title</title>
</head><body><h1>Sample
Text</h1></body>");
[Link] =
"Hello folks";
54
The Navigator Object
alert([Link]
t);
The The navigator The
browser in the browser userAgent
window window (browser
ID)
55
The Screen Object
The screen object contains
information about the display
[Link](0, 0);
x = [Link];
y = [Link];
[Link](x, y);
56
Document and Location
document object
Provides some built-in arrays of
specific objects on the currently
loaded Web page
[Link][0].href = "[Link]";
[Link](
"This is some <b>bold text</b>");
[Link]
Used to access the currently open
URL or redirect the browser
[Link] =
"[Link] 57
Form Validation –
Example
[Link]
function checkForm()
{
var valid = true;
if ([Link] == "") {
alert("Please type in your first name!");
[Link]("firstNameError").
[Link] = "inline";
valid = false;
}
return valid;
}
…
<form name="mainForm" onsubmit="return
checkForm()">
<input type="text" name="firstName" />
…
</form>
58
The Date Object
The Date object provides date /
calendar functions
[Link]
var now = new Date();
var result = "It is now " + now;
[Link]("timeField")
.innerText = result;
...
<p id="timeField"></p>
59
Timers: setTimeout()
Make something happen (once)
after a fixed delay
var timer = setTimeout('bang()',
5000);
5 seconds after this
statement executes,
this function is called
clearTimeout(timer);
Cancels the
timer
60
Timers: setInterval()
Make something happen
repeatedly at fixed intervals
var timer = setInterval('clock()',
1000);
This function is
called continuously
per 1 second.
clearInterval(timer);
Stop the
timer.
61
Timer – Example
[Link]
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = [Link]();
var min = [Link]();
var sec = [Link]();
[Link]("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
62
Debugging
JavaScript
Debugging JavaScript
Modern browsers have JavaScript
console where errors in scripts are
reported
Errors may differ across browsers
Several tools to debug JavaScript
Microsoft Script Editor
Add-on for Internet Explorer
Supports breakpoints, watches
JavaScript statement debugger; opens
the script editor
64
Firebug
Firebug – Firefox add-on for
debugging JavaScript, CSS, HTML
Supports breakpoints, watches,
JavaScript console editor
Very useful for CSS and HTML too
You can edit all the document real-
time: CSS, HTML, etc
Shows how CSS rules apply to
element
Shows Ajax requests and responses
Firebug is written mostly in 65
Firebug (2)
66
JavaScript Console
Object
The console object exists only if
there is a debugging tool that
supports it
Used to write log messages at
runtime
Methods of the console object:
debug(message)
info(message)
log(message)
warn(message) 67
Introduction to
JavaScript
?
?
?
?
Questions
?
?
?
?
?
? ?
Home Work
1. Create an HTML page that has two text
fields (first name and last name) and
a button. When the user clicks the
button, a message should show the
text in the text fields followed by the
current time.
2. Create a Web page that asks the user
about his name and says goodbye to
him when leaving the page.
3. Modify the previous HTML page to have
a text field for email address and on
clicking the button check if the email is
valid (it should follow the format 69
Home Work
5. Create a drop-down menu
Use table for the main menu blocks
Use hidden <DIV> elements (display:
none; position:absolute; top:30px)
Use JavaScript and onmouseover and
onmouseout event to change display:
none/block
70
Home work
6. Create a DTHML page that has <div>
containing a text that scrolls from right
to left automatically
Use setInterval() function to move
the text at an interval of 500 ms
Use overflow:hidden for the <div>
Use scrollLeft and scrollWidth
properties of the <div> element
71