Web Engineering Javascript (Part 1) : Muhammad Umair Naru Department of Computer Science
Web Engineering Javascript (Part 1) : Muhammad Umair Naru Department of Computer Science
JavaScript (Part 1)
Muhammad Umair Naru
Department of Computer Science
JavaScript Lecture I
http://wp.netscape.com/eng/mozilla/3.0/handbook
/javascript/index.html
Introduction to JavaScript
• NOT Java
– JavaScript was developed by Netscape
– Java was developed by Sun
• Designed to ‘plug a gap’ in the techniques
available for creating web-pages
– Client-side dynamic content
• Interpreted
1
JavaScript vs. Java
• Complementary
– JavaScript
• Cannot draw, multi-thread, network or do I/O
– Java
• Cannot interact with Browser or control content
2
What is it used for today?
• Handling User Interaction
– Doing small calculations
– Checking for accuracy and appropriateness of data entry from
forms
– Doing small calculations/manipulations of forms input data
– Search a small databased embedded in the downloaded page
– Save data as cookie so it is there upon visiting the page
• Generating Dynamic HTML documents
• Examples
– Bookmarklets
– Google Maps
– Google Suggest
JavaScript Shell
• http://www.squarefree.com/shell/
• http://www.squarefree.com/jsenv/
• http://www.mozilla.org/rhino/shell.html
3
JavaScript Syntax - Variables and
Literals
• Declaration
– Explicit: var i = 12; // no ‘var’ in declaration
– Implicit: i = 12;
• Variable Scope
– Global
• Declared outside functions
• Any variable implicitly defined
– Local
• Explicit declarations inside functions
4
JavaScript Syntax - Operators
• Key Comparison Operators
> number on the left must be greater than the number on the right
< number on the right must be greater than the number on the left
<= number on the right must be greater than or equal to the number on the
left
>= number on the right must be less than or equal to the number on the left
!= the numbers or objects or values must not be equal
! Logical NOT
|| Logical OR
+= the object on the left = the object on the left + the value on the right
this also works when appending strings
-= the object on the left = the object on the left - the value on the right
++ / -- Increment / Decrement a number
5
JavaScript Syntax – Control and
Looping
• ‘if’ statement
if ( boolean statement ) {
…
} else {
…
}
• ‘switch’ statement
switch ( myVar ) {
case 1:
// if myVar is equal to 1 this is executed
case “two”:
// if myVar is equal to “two” this is executed
case default:
// if none of the cases above are satisfied OR if no
// ‘break’ statement are used in the cases above,
// this will be executed
}
6
JavaScript Syntax - Functions
• Calling a function the same way you would
in C
myFunc(arg1, arg2, …);
• Declaring a function using the ‘function’
keyword
– No return type, nor typing of arguments
function add(numOne, numTwo) {
return numOne + numTwo;
}
JavaScript Output
• The document objects allows printing
directly into the browser page (amongst
other things)
• window object is implied
• Writing in text or HTML with script
– No line-break
document.write(“I am <B>BOLD</B>”);
– With line-break
document.writeln(“I am <U>underlined</U>”);
7
Code Example
• Variables, Loops, and Output
Objects in JavaScript
• Not Object Oriented – but Object-Based
• Easy to declare and create JavaScript
Objects
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
8
Objects in JavaScript
• Accessing object’s properties
var someGuy = new Person(“Shawn”, 28);
document.writeln(‘Name: ‘ + someGuy.name);
Objects in JavaScript
• Object Functions
– Functions are just properties like any other property of an object (name,
age, etc…)
function displayName() {
document.writeln(“I am “ + this.name);
}
9
Objects in JavaScript
• Object Functions
– Then to call the function on the object
Object Example
• Using objects
10
Inheritance in JavaScript
• No built-in inheritance
• Runtime Inheritance: Clone objects and add extra
properties
• For next week: Come prepared with at least one way of
doing inheritance in JavaScript. Google is your friend.
Person
Prof Student
Built-in Objects
• Number, Boolean, String
– Primitive types are automatically coerced into Objects when assigned to
variables.
• var str = “abc”;
• var is a String object
– Number and Boolean are boring!
– String has some helpful properties/functions:
• length
• toUpperCase
• substring
• link
• Date
– No properties, but contains a bunch of methods for getting, setting and
manipulating dates.
• Math
– Calculate PI, find the SIN or COS of an angle, etc..
11
Arrays
• Creating Arrays
var a = new Array(); // empty array
var b = new Array(“dog”, 3, 8.4);
var c = new Array(10); // array of size 10
var d = [2, 5, ‘a’, ‘b’];
• Associative Arrays
var e = new Array();
e[“key”] = “value”;
e[“numKey”] = 123;
Arrays
• Properties and Methods
– length
– join()
– reverse()
– sort()
– concat()
– slice()
– splice()
– push() / pop()
– shift() / unshift()
– toString()
– …….
12
Array Example
• General Usage
Embedding in HTML
• Directly vs. Indirectly
– Directly
<script type="text/javascript">
…code here...
</script>
– Indirectly
<script type="text/javascript" src="test.js">
</script>
• Location: <HEAD> vs. <BODY>
– Code directly or indirectly placed in the <HEAD> element is
made available to be called later on in the document.
– Code directly or indirectly placed in the <BODY> will be run
when the document is parsed.
• Best to declare all functions in the HEAD and use the
appropriate Event Handler to call the functions.
13
Now we get into the cool stuff
The real power of JavaScript
Window Controls
Event Handlers
DOM
Cookies
And much much more…
14
Window – Built-in Functions
• alert("message")
• window.close()
• confirm("message")
• focus()
• open("URLname","Windowname",["options"])
– height, weight, alwaysRaised, location,
menubar, etc..
open(“http://google.com”, “My Google”,
“toolbar=no,alwaysRaised=yes”);
Window Example
• Controlling one browser window from
another
15
Browser – Built-in Objects
• window.location
– href represents a complete URL.
– hostname represents the concatenation host:port.
– window.location.href=“http://google.com”;
• window.history
– length reflects the number of entries in the history
list
– history.go(-1)
– history.back()
Form Object
• Form objects can be accessed by:
window.document.myForm OR
window.document.forms[0]
• Properties
– action, target, length, method, etc…
• Functions
– window.document.myForm.submit();
– window.document.myForm.reset();
• Accessing Form Field Values
– window.document.myForm.firstname.value
16
(D)HTML Object Hierarchy
Event Handlers
• Events are actions that occur usually as a
result of something the user does. For
example, clicking a button is an event, as
is changing a text field or moving the
mouse over a hyperlink.
17
Event Handlers
• You can use event handlers, such as
onChange and onClick, to make your
script react to events.
<input type=“button” onClick=“javascript:doButton()>
<select onChange=“javascript:doChange()”>
<form onSubmit=“javascript:validate()”>
<body onLoad=“javascript:init()”>
Example
• Use event handlers, functions and
document / form object to change
information on the page
18
DOM – Document Object Model
• W3C DOM, “The DOM”, DOM Level (1/2/3)
• Method of accessing / modifying XML information on the page
• Tree structure of all HTML elements, including attributes and the text they
contain.
• Contents can be modified or deleted
• New elements can be created and inserted into the DOM Tree
• The concept is used in other languages, such as Java (google: Java DOM)
tr tr id=“mytable”
childNodes childNodes
td td
attribues childNodes …
19
Document Object
• The document object is the JavaScript
interface to the DOM of any HTML page.
• Accessing elements:
– By name
document.getElementsByTagName(‘td')[indexOfColumn]
– By ID
document.getElementById('id')
window.setTimeout('myFunc()',timeInMillise
conds);
var myinterval =
window.setInterval('myFunc()',timeInMillis
econds);
20
Time Delay Example
Regular Expressions
• You have seen this before!
• RegExp object
var beerSearch = /beer/
var beerSearch = new RegExp(“beer”)
• Methods
– search pattern and return results in a array
exec(str)
– returns true if match
test(str)
21
Regular Expressions
• Special Characters
\w Alphanumeric
\d Numerical digit
\s White spaces
. Anything other than newline
[abcde] Any of a,b,c,d,e
[a-e] Same as above
[^a-e] Anything but a to e
exp?,exp+,exp* 0 or 1, 1 or more, 0 or more
exp{x,y} At least x but less than y
expA | expB expA or expB
• JavaScript RegEx Resources
– http://wsabstract.com/javatutors/redev.shtml
– http://www.devguru.com/Technologies/ecmascript/quickref/regexp_spec
ial_characters.html
22
JavaScript Resources
• JavaScript Bible
• JavaScript: The Definitive Guide
• http://www.w3schools.com/js/default.asp
• http://wp.netscape.com/eng/mozilla/3.0/ha
ndbook/javascript/index.html
23