Basic JavaScript
Basic JavaScript
Noor ullah
khan
Table of Contents
What is DHTML?
DHTML Technologies
XHTML, CSS, JavaScript, DOM
Introduction to JavaScript
What is JavaScript
Implementing JavaScript into Web
pages
In <head> part
In <body> part
In external .js file
2
JavaScript Syntax
JavaScript operators
JavaScript Data Types
JavaScript Pop-up boxes
alert, confirm and prompt
DOM
Events
DHTML
Dynamic Behavior at the Client Side
What is DHTML?
CSS
JavaScri
pt
DOM
5
JavaScript
JavaScript
Client-side technology
Embedded in your HTML page
Interpreted by the Web browser
JavaScript Advantages
10
11
12
Highly recommended
The .js files get cached by the
browser
13
JavaScript When is
Executed?
/>
onclick="alert('clicked!')"
Executed when the event
is fired by
14
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>
15
<html>
external<head>
JavaScript.html
<script src="sample.js" type="text/javascript">
</script>
</head>
The <script src=""> tag is
<body>
always empty.
<button onclick="sample()" value="Call
JavaScript
function from sample.js" />
</body>
External
JavaScript file:
</html>
function sample() {
alert('Hello from sample.js!')
}
sample.j
s
16
The
JavaScript
Syntax
JavaScript Syntax
18
Data Types
Arrays
Everything is Object
20
String Operations
What is "9" + 9?
alert("9" + 9);
// fat cats
// 99
// 18
21
Confirmation box
Contains text, [OK] button and
[Cancel]
button:
confirm("Are
you sure?");
Prompt box
Contains text, input field with
prompt ("enter amount", 10);
default value:
23
sum-ofnumbers.html
<html>
Sum of Numbers
Example
<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;
}
</script>
</head>
24
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="calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
25
JavaScript Prompt
Example
prompt.ht
ml
price = prompt("Enter
the price",
"10.00");
alert('Price + VAT = ' + price * 1.2);
26
Conditional Statement
(if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
Symb
>
ol
Meaning
Greater than
<
Less than
>=
==
Greater than or
equal to
Less than or equal
to
Equal
!=
Not equal
<=
27
Conditional Statement
(if) (2)
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 + ";");
}
28
Switch Statement
Loops
Functions
Code structure splitting code into
parts
Data comes in, processed, result
returned
Parameters
function average(a, b,
c)
{
var total;
total = a+b+c;
return total/3;
}
come in here.
Declaring
variables is
optional. Type
is never
declared.
Value
returned here.
31
Function
Arguments
andrequired
ReturntoValue
Functions are not
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() {passed via arguments array
arguments
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
functions-demo.html
32
Document
Object Model
(DOM)
Accessing Elements
var arr =
document.getElementsByName("some_name")
DOM Manipulation
DOM-manipulation.html
function change(state) {
var lampImg =
document.getElementById("lamp");
lampImg.src = "lamp_" + state + ".png";
var statusDiv =
document.getElementById("statusDiv");
statusDiv.innerHTML = "The lamp is " +
state";
}
<img src="test_on.gif"
36
Common Element
Properties
Common Element
Properties (2)
Accessing Elements
through the DOM Tree
Structure
element.childNodes
element.parentNode
element.nextSibling
element.previousSibling
element.firstChild
element.lastChild
39
Accessing Elements
through the DOM Tree
Example
var el = document.getElementById('div_tag');
alert (el.childNodes[0].value);
alert (el.childNodes[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-
demo.html
40
DOM Events
DOM Events
var
Canimg
be= accessed through the DOM:
document.getElementById("myImage");
img.onclick = imageClicked;
42
44
Mouse events:
onclick, onmousedown, onmouseup
onmouseover, onmouseout,
onmousemove
Key events:
onkeypress, onkeydown, onkeyup
Only for input fields
Interface events:
onblur, onfocus
onscroll
45
Form events
Miscellaneous events
onload, onunload
Allowed only for the <body> element
Fires when all content on the page
was loaded / unloaded
46
onload event
<html>
onload.ht
ml
<head>
<script type="text/javascript">
function greet() {
alert("Loaded.");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
47
The Built-In
Browser
Objects
Built-in Browser
Objects
document
holds information the current loaded
document
screen
Holds the user display properties
browser
49
DOM Hierarchy
Example
window
navigato
r
screen
documen
t
form
history
location
form
butto
n
form
50
window.open()
windowopen.html
51
The
browser
window
The navigator
in the browser
window
The
userAgent
(browser
ID)
52
53
document object
Provides some built-in arrays of
specific objects on the currently
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/";
54
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>
55
Debugging
JavaScript
Debugging JavaScript
Firebug
Firebug (2)
59
Introduction to
JavaScript
? ?
?
Questions
?
Exercises
Create an HTML page
containing a table. Write a
script to color the table rows
in alternating colors.
2. 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.
1.
61
Exercises (2)
Create a Web page displaying a
list of products. For each product,
when the mouse is hold over it
show a tooltip with additional info.
5. Implement a JavaScript based
temperature converter between Celsius
and Fahrenheit.
6. Implement a text-scrolling script that
scrolls a long text message inside a
<div>. You could use two divs one
inside the other and move the left
position of the inner div at interval of
200 milliseconds.
4.
62
Exercises (3)
7.
63