JavaScript-Basics 1
JavaScript-Basics 1
JavaScript
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
2
DTHML = HTML + CSS +
JavaScript
HTML defines Web sites content
through semantic tags (headings,
paragraphs, lists, …)
CSS defines 'rules' or 'styles' for
presenting every aspect of an
HTML document
Font (family, size, color, weight,
etc.)
Background (color, image, position,
repeat)
Position and layout (of any object 3
JavaScript
JavaScript is a front-end scripting
language developed by Netscape
for dynamic content
Lightweight, but with limited
capabilities
Can be used as object-oriented
language
Client-side technology
Embedded in your HTML page
Interpreted by the Web browser
4
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 5
What Can JavaScript
Do?
Can handle events
Can read and write HTML elements
and modify the DOM tree
Can validate form data
Can access / modify browser
cookies
Can detect the user’s browser and
OS
Can be used as object-oriented
language 6
The First Script
first-
script.html
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
7
Another Small Example
small-
example.html
<html>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
8
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="scripts.js"
tag the head
type="text/javscript">
<!– code placed here will not be executed! --
>Files usually have .js extension
</script>
9
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="logo.gif"
tag attributes
onclick="alert('clicked!')" />
Executed when the event is fired by 10
Calling a JavaScript
Function from Event
Handler – Example
<html> image-
<head> onclick.html
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
11
Using External Script
Files
Using external script files:
<html> external-
<head>
JavaScript.html
<script src="sample.js" type="text/javascript">
</script>
</head> The <script> tag is
<body> always empty.
<button onclick="sample()" value="Call
JavaScript
function from sample.js" />
</body>
</html>
External JavaScript file:
function sample() {
alert('Hello from sample.js!')
} sample.j
s 12
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 13
Sum of Numbers –
Example
sum-of-
numbers.html
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
14
</script>
Sum of Numbers –
Example (2)
sum-of-numbers.html
(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>
15
JavaScript Prompt –
Example
prompt.ht
ml
price = prompt("Enter the price",
"10.00");
alert('Price + VAT = ' + price * 1.2);
16
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
17
Conditional Statement
(if) (2)
The condition may be of Boolean or
integer type:
conditional-statements.html
var a = 0;
var b = true;
if (typeof(a)=="undefined" ||
typeof(b)=="undefined") {
document.write("Variable a or b is undefined.");
}
else if (!a && b) {
document.write("a==0; b==true;");
} else {
document.write("a==" + a + "; b==" + b + ";");
}
18
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.
19
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 < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); functions-demo.html
20
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 22
Accessing Elements
Access elements via their ID
attribute
var elem = document.getElementById("some_id")
var img =
Can be accessed through the DOM:
document.getElementById("myImage");
img.onclick = imageClicked;
30
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 31
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
document.event
Some of the names of the event’s
object properties are browser-
specific
32
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 33
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
34
onload Event – Example
onload event onload.ht
<html> ml
<head>
<script type="text/javascript">
function greet() {
alert("Loaded.");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
35
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 37
DOM Hierarchy –
Example
window
form form
butto form
n
38
Opening New Window –
Example
window.open()
window-
var newWindow = window.open("", open.html
"sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");
newWindow.document.write(
"<html><head><title>
Sample Title</title>
</head><body><h1>Sample
Text</h1></body>");
newWindow.status =
"Hello folks";
39
The Navigator Object
alert(window.navigator.userAgen
t);
40
The Screen Object
The screen object contains
information about the display
window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);
41
Document and Location
document object
Provides some built-in arrays of
specific objects on the currently
loaded Web page
document.links[0].href = "yahoo.com";
document.write(
"This is some <b>bold text</b>");
document.location
Used to access the currently open
URL or redirect the browser
document.location =
"http://www.yahoo.com/"; 42
Form Validation –
Example
form-validation.html
function checkForm()
{
var valid = true;
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
document.getElementById("firstNameError").
style.display = "inline";
valid = false;
}
return valid;
}
…
<form name="mainForm" onsubmit="return
checkForm()">
<input type="text" name="firstName" />
…
</form>
43
The Math Object
The Math object provides some
mathematical functions
math.ht
for (i=1; i<=20; i++) { ml
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write(
"Random number (" +
i + ") in range " +
"1..10 --> " + x +
"<br/>");
}
44
The Date Object
The Date object provides date /
calendar functions
dates.html
var now = new Date();
var result = "It is now " + now;
document.getElementById("timeField")
.innerText = result;
...
<p id="timeField"></p>
45
Timers: setTimeout()
Make something happen (once)
after a fixed delay
Cancels the
timer
46
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.
47
Timer – Example
timer-demo.html
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
document.getElementById("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
48