All Rights Reserved © Valores Corporativos Softtek S.A. de C.V. 2015.internal
All Rights Reserved © Valores Corporativos Softtek S.A. de C.V. 2015.internal
Disclaimer
Document Name:
Data Classification: INTERNAL
Disclaimer
The contents of this document are property of Softtek, and are for internal use only. Any reproduction in whole
or in part is strictly prohibited without the written permission of Softtek.
This document is subject to change. Comments, corrections or questions should be directed to the author.
Revision Chart
The following chart list the revisions made to this document. Use this to describe the changes and additions
each time this document is re-published. The description should be detailed as possible and include the names
of the reviewers who request the changes.
Version
No.
Version Date
Types of Changes
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015. Internal.
Owner/Author
Date of Review /
Expiration
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015. Internal.
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
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
Performing complex calculations
Custom HTML controls, e.g. scrollable table
Implementing AJAX functionality
5
JavaScript When is
Executed?
Calling a JavaScript
Function from Event
Handler Example
<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>
11
<html>
external<head>
JavaScript.html
<script src="sample.js" type="text/javascript">
</script>
</head>
The <script> tag is always
<body>
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
12
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# delegates)
14
Data Types
JavaScript data types:
Numbers (integer, floating-point)
Boolean (true / false)
Arrays
Everything is Object
Every variable can be considered as object
For example strings and arrays have member
functions:
objects.html
16
String Operations
The + operator joins strings
string1 = "fat ";
string2 = "cats";
alert(string1 + string2);
// fat cats
What is "9" + 9?
alert("9" + 9);
// 99
// 18
17
Confirmation box
you sure?");
20
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>
21
prompt.html
JavaScript Prompt
Example
22
Symbo
l>
Meaning
Greater than
<
Less than
>=
<=
==
Equal
!=
Not equal
23
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 + ";");
}
24
Switch Statement
The switch statement works like in C#:
switch (variable) {
switch-statements.html
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
25
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);
}
loops.html
26
Functions
Code structure splitting code into parts
Data comes in, processed, result returned
function average(a, b,
c)
{
var total;
total = a+b+c;
return total/3;
}
Parameters come
in here.
Declaring
variables is
optional. Type is
never declared.
Value returned
here.
27
Function Arguments
and Return Value
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
functions-demo.html
alert(sum(1, 2, 4));
28
Document
Object Model
(DOM)
30
Accessing Elements
Access elements via their ID attribute
var elem = document.getElementById("some_id")
var arr =
document.getElementsByName("some_name")
Via
tag name
var imgTags = el.getElementsByTagName("img")
31
DOM Manipulation
Once we access an element, we can read
and write its attributes
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"
32
Common Element
Properties
34
Accessing Elements
through the DOM Tree
Structure
35
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
DOM:
var img =
document.getElementById("myImage");
img.onclick = imageClicked;
38
39
40
Key events:
onkeypress, onkeydown, onkeyup
Only for input fields
Interface events:
onblur, onfocus
onscroll
41
Miscellaneous events
onload, onunload
Allowed only for the <body> element
Fires when all content on the page was loaded /
unloaded
42
onload.html
<html>
<head>
<script type="text/javascript">
function greet() {
alert("Loaded.");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
43
The Built-In
Browser Objects
document
holds information the current loaded document
screen
Holds the users display properties
browser
Holds information about the browser
45
window
navigator
screen
document
form
history
location
form
button
form
46
47
The
browser
window
The navigator in
the browser
window
The
userAgent
(browser ID)
48
49
document.location
50
</form>
51
math.html
dates.html
53
Timers: setTimeout()
Make something happen (once) after a fixed
delay
var timer = setTimeout('bang()',
5000);
Cancels the
timer
54
Timers: setInterval()
Make something happen repeatedly at fixed
intervals
var timer = setInterval('clock()',
1000);
Stop the
timer.
55
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" />
56
Debugging JavaScript
Debugging JavaScript
Modern browsers have JavaScript console
where errors in scripts are reported
Errors may differ across browsers
58
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
Firebug (2)
60
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015. Internal.
62
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015. Internal.
63
Q&A
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015.Internal.
All Rights Reserved Valores Corporativos Softtek S.A. de C.V. 2015. Internal.