1
JavaScriptCCSS TEAM:Eng. Musavir Iftekhar Bhatti
2
What is JavaScript ?
Client-side language.( run in the client browser) Scripting language. (interpreted in run-time) Not compile like other language (C#, C++, VB.Net etc). JavaScript code can be inserted directly in the HTML or can place it in a separate file with the .js extension and link the web page with the .js file. Use in web browser for making a website more dynamic. Supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and
most of the other modern web browsers. Contains variable, array,object,operators and function.
3
Usage of JavaScript
Used to perform operations that would otherwise encumber the server, like form validation input.
Can be easily used to interact with HTML elements such as validate text fields, disable buttons, validate forms, or change the background color of page.
Create dynamic page React to events such the user enter name whenever the page
load for 1st time. User can used entered value for welcome page.
4
Java VS JavaScript
Java JavaScript
Sun Microsystems Netscape
Much larger and advanced set of commands.
Much smaller and simpler set of commands .
Applets distinct from HTML (accessed from HTML pages).
Code integrated with, and embedded in, HTML.
Variable data types must be declared (strong typing).
Variable data types not declared (loose typing).
Compiled on server before execution on client.
Interpreted (not compiled) by client.
5
How to Put a JavaScript Into an HTML Page
JavaScript is written in the same way as HTML in a text editor (Notepad)
JavaScript implementation was quite similar to CSS; you can link to outside files (with the file extension .js) , or write blocks of code into your HTML documents with the <script> tag
6
<html> <body> <script type="text/javascript">
document.write("HelloWorld!")</script> </body> </html>
The above code will produce this output on the HTML page.
HelloWorld!!
7
To insert a JavaScript into an HTML page, we use the <script> tag.
The <script type="text/javascript"> and </script> tells where the JavaScript starts and ends
The script tag encloses any script code you want to use The type attribute alert the browser to the type of script it is about
to deal with, it helps in code interpretation.
8
The comments around the script are there so that old browsers that don’t understand the script tag won’t display the code as text on the page.
If the browser can do JavaScript, then it will ignore the comments.
9
<html> <body> <script type="text/javascript"> ... </script> </body> </html>
10
The word document.write is a standard JavaScript command for writing output to a page.
If we had not entered the <script> tag, the browser would have treated the document.write("Hello World!") command as pure text, and just write the entire line on the page.
This will be the output
document.write("Hello World!")
11
You can place an unlimited number of scripts in your document, so that you can have scripts in both the body and the head section.
<html><head><script type=“text/javascript”>……</script></head><body><script type=“text/javascript”>……</script></body>
12
External scripts
To import scripts from external JavaScript files, save the code in the text file with the .js extension; without the script tags and comment.
13
A simple example for external scripts
Save as main.html
Save as hello.js
<html><head><body><script language="javascript" type="text/javascript"src="hello.js"></body></head></script>
var hello = 'Hello World';document.write(hello);
14
Output
Hello World!
15
<noscript> tag
The noscript element is used to define an alternate content (text) if a script is NOT executed.
This tag is used for browsers that recognizes the <script> tag, but does not support the script in it.
If a browser supports scripting, it will not display the text in the noscript element.
16
Example
<noscript>
Your browser does not support JavaScript!
</noscript>
17
<html>
<head>
<body>......<script type="text/javascript"><!--document.write("Hello World!")//--></script><noscript>
Your browser does not support JavaScript!
</noscript>......</body>
</head>
</html>
18
Object in JavaScript
JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.
We will only look at the built-in JavaScript objects, and how they are used. The next slides will explain each built-in JavaScript object in detail.
Note that an object is just a special kind of data. An object has properties and methods.
19
Object in JavaScript
The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram. The window itself is an object that have document in it. In document it has another object such as images and forms. Each of these objects have its own properties and methods.
20
Object in JavaScript - properties
•Properties are the values associated with an object.
•Below examples shows how to access length property of document object to return the number of characters in a string.
<script type="text/javascript">
var txt="Hello World!“document.write(txt.length)
</script>
•The output of the code above will be:12 ( H e l l o [space] W o r l d ! )
21
Object in JavaScript - methods
•Methods are the actions that can be performed on objects.
•In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:
<script type="text/javascript">var str="Hello world!" document.write(str.toUpperCase())
</script>
•The output of the code above will be:
HELLO WORLD!
22
The most commonly used JavaScript objects
Object Properties Methods
Window defaultStatus, frames, opener, parent, scroll, self, status, top, window
Alert, blur ,close, confirm, focus, open, prompt, clearTimeout, setTimeout
Frame defaultStatus, frames, opener, parent, scroll, self, status, top, window
Alert, blur, close, confirm, focus, open, prompt, clearTimeout, setTimeout
Location Hash, host, hostname, href, pathname, por, protocol, search
Reload, replace
History Length, forward, go Back
Navigator appCodeName, appName, appVersion, mimeTypes, plugins, userAgents
javaEnabled
Documents alinkColor, anchors, applets, ares, bgColor, cookie, fgColor, forms, images, lastModified, linkColor, links, location, referrer, title, vlinkColor
Clear, close, open, write, writeln
Image Border, complete, heigth, hspace, lowwsrc, vspace, width
None
Form Action, elements, encoding, FileUpload, method, name, target
Submit, reset
Text defaultValue, name, type, value Focus, blur, select
23
The most commonly used Built-in JavaScript Objects
Objects Properties Methods
Array Length Join, reverse, sort xx
Date None getDate, getDay, getHours, getMinutes, getMonth, getSeconds, getTime, getTimeZoneoffset, getYear, parse, prototype, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC
String Length, Prototype Anchor, big, blink, bold, charAt, fixed, fontColor, fontSize, indexOf, italics, lastIndexOf, link, small, split, strike, sub, substring, sup,
toLowerCase,toUpperCase
24
Built-in JavaScript Objects
String Object Date Object Array Object Math Object Boolean Object
25
The String object is used to manipulate a stored piece of text. The following example uses the length property of the String
object to find the length of a string:
<script type="text/javascript">
var txt="Hello World!”document.write(txt.length)
</script>
The above code will result in following output: 12
Built-in JavaScript Objects - String
26
The Date object is used to work with dates and times. Example below shows how to use Date() method to get today’s date:
<script type="text/javascript">
document.write(Date())
</script>
The output will be:
Mon Nov 05 15:51:51 2007
Built-in JavaScript Objects - Date
27
This 2nd example shows how to use getTime() method to calculate years since 1970:
<script type="text/javascript">var minutes = 1000*60var hours = minutes*60var days = hours*24var years = days*365var d = new Date()var t = d.getTime()var y = t/years
document.write("It's been: " + y + " years since 1970/01/01!")</script>
The output will be: It's been: 37.86941401639396 years since 1970/01/01!
Built-in JavaScript Objects - Date
28
The Array object is used to store a set of values in a single variable name.
1. We create a new Array by assigning it to a new keyword, myArray:
var mycars=new Array() mycars[0]=“Lotus" mycars[1]="Volvo" mycars[2]="BMW"
ORvar mycars=new Array("Saab","Volvo","BMW")
Built-in JavaScript Objects - Array
29
2. We can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:document.write(mycars[0])
will result in the following output:Lotus
3. To modify a value in an existing array, just add a new value to the array with a specified index number and then try to access it:
mycars[0]=“Lexus”document.write(mycars[0])
will result in the following output:Lexus
Built-in JavaScript Objects - Array
30
The Math object allows you to perform common mathematical tasks.
The Math object includes several mathematical values and functions. You do not need to define the Math object before using it.
Built-in JavaScript Objects - Math
31
JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object.
These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.
You may reference these values from your JavaScript like this:Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E
Built-in JavaScript Objects – Math - values
32
In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available.
The following example uses the round() method of the Math object to round a number to the nearest integer:
document.write(Math.round(4.7)) The code above will result in the following output:
5
Built-in JavaScript Objects – Math - methods
33
The Boolean object is an object wrapper for a Boolean value. The Boolean object is used to convert a non-Boolean value to a
Boolean value (true or false). We define a Boolean object with the new keyword. The following
code line defines a Boolean object called myBoolean:
var myBoolean=new Boolean()
Built-in JavaScript Objects - Boolean
34
If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false").
Example of Boolean object with initial value of false:var myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean("") var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)
Example of Boolean object with initial value of true:var myBoolean=new Boolean(true) var myBoolean=new Boolean("true") var myBoolean=new Boolean("false") var myBoolean=new Boolean("Richard")
Built-in JavaScript Objects - Boolean
35
How to create an object?
1. Create a direct instance of an object
2. Create template of an object
36
A bird (object)
Fly () name
age
EyeColor
Eat()
Drink()
METHODS PROPERTIES
Object
37
1. Direct Instance
Add few properties to the bird
BirdObj=new Object()
BirdObj.name=“MorningBird“
BirdObj.age=2
BirdObj.eyecolor=“green"
Add methods to the birdBirdObj.fly = fly
BirdObj.eat = eat
BirfObj.Breath = breath
38
2. Create Template to the object
function Bird(name,age,eyecolor)
{ this.name=name
this.age=age
this.eyecolor=eyecolor
}
When you have template, then you can create new instance of the object :
myBird= new Bird (“Parrot”, 2, “blue”)
39
You can also add some methods to the bird object. This is also done inside the template:
function Bird(name,age,eyecolor) { this.name=name
this.age=age this.eyecolor=eyecolor
this.habitat = habitat new method}
That methods are just functions attached to objects. Then we will have to write the habitat() function:
function habitat(new_habitat) {
this.habitat=new_habitat }
Eg : myBird.habitat(“Pond”)
40
DOM: What is it?DOM Specification:
“a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. … [DOM] provides a standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them.”
41
DOM: Implementations
Java-based parsers (e.g. Sun Project X, IBM XML4J, Apache Xerces)
MS IE5 browser: COM programming interfaces for C/C++ and MS Visual Basic, ActiveX object programming interfaces for script languages
42
Object-based document modelling
Object model coversstructure of a document
behaviour of a document and its constituent objects
DOM definesinterfaces and objects for representing and manipulating documents
semantics of these interfaces
relationships between interfaces and objects
43
DOM structure model Based on O-O concepts:
methods (to access or change object’s state)interfaces (declaration of a set of methods) objects (encapsulation of data and methods)
Roughly similar to the XSLT/XPath data model
a parse tree
44
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form="00"form="00"type="estimatedbill"type="estimatedbill"
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
<invoice><invoice> <invoicepage form="00" <invoicepage form="00" type="estimatedbill">type="estimatedbill"> <addressee><addressee> <addressdata><addressdata> <name>Leila Laskuprintti</name><name>Leila Laskuprintti</name> <address><address> <streetaddress>Pyynpolku 1<streetaddress>Pyynpolku 1 </streetaddress></streetaddress> <postoffice>70460 KUOPIO<postoffice>70460 KUOPIO </postoffice></postoffice> </address></address> </addressdata></addressdata> </addressee> ...</addressee> ...
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
XML DOM structure modelXML DOM structure model
45
HTML DOM structure modelHTML DOM structure model
The DOM presents an HTML document as a tree-structure (a The DOM presents an HTML document as a tree-structure (a node tree), with elements, attributes, and text.node tree), with elements, attributes, and text.
46
The application support and intermediate DOM which existed before the creation of DOM Level 1.Example include the DHTML object model or the Netscape intermediate DOM.Level 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process.
Structure of DOM Level 0
47
Structure of DOM Level 1Two parts:I: DOM Core Interfaces
Fundamental interfaces low-level interfaces to structured documents
Extended interfaces (next page)XML specific: CDATASection, DocumentType, Notation, Entity, EntityReference, ProcessingInstruction
II: DOM HTML Interfaces more convenient to access HTML documentsLevel 1 intentionally limited to representation and manipulation of document structure and content
document instance only; no access to the contents of a DTD
48
DOM Level 2
support for namespacesaccessing elements by ID attribute valuesoptional features
interfaces to document views and stylesheetsan event model (for, say, user actions on elements)methods for traversing the document tree and manipulating regions of document (e.g., selected by the user of an editor)
49
Consists of 6 different specifications:
1. DOM Level 3 Core;2. DOM Level 3 Load and Save3. DOM Level 3 XPath;4. DOM Level 3 Views and Formatting;5. DOM Level 3 Requirements; and6. DOM Level 3 Validation, which further
enhances the DOM
DOM Level 3
50
Core Interfaces: Node & its variants
NodeNode
CommentComment
DocumentFragmentDocumentFragment AttrAttr
TextText
ElementElement
CDATASectionCDATASection
ProcessingInstructionProcessingInstruction
CharacterDataCharacterData
EntityEntityDocumentTypeDocumentType NotationNotation
EntityReferenceEntityReference
““Extended Extended interfaces”interfaces”
DocumentDocument
51
DOM interfaces: DOM interfaces: NodeNode
invoice
invoicepage
name
addressee
addressdata
address
form="00"type="estimatedbill"
Leila Laskuprintti streetaddress postoffice
70460 KUOPIOPyynpolku 1
NodeNodegetNodeTypegetNodeTypegetNodeValuegetNodeValuegetOwnerDocumentgetOwnerDocumentgetParentNodegetParentNodehasChildNodeshasChildNodes getChildNodesgetChildNodesgetFirstChildgetFirstChildgetLastChildgetLastChildgetPreviousSiblinggetPreviousSiblinggetNextSiblinggetNextSiblinghasAttributeshasAttributes getAttributesgetAttributesappendChild(newChild)appendChild(newChild)insertBefore(newChild,refChild)insertBefore(newChild,refChild)replaceChild(newChild,oldChild)replaceChild(newChild,oldChild)removeChild(oldChild)removeChild(oldChild)
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
52
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form="00"form="00"type="estimatedbill"type="estimatedbill"
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
DocumentDocumentgetDocumentElementgetDocumentElementcreateAttribute(name)createAttribute(name)createElement(tagName)createElement(tagName)createTextNode(data)createTextNode(data)getDocType()getDocType()getElementById(IdVal)getElementById(IdVal)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
DOM interfaces: DOM interfaces: DocumentDocument
53
DOM interfaces: DOM interfaces: ElementElement
invoiceinvoice
invoicepageinvoicepage
namename
addresseeaddressee
addressdataaddressdata
addressaddress
form="00"form="00"type="estimatedbill"type="estimatedbill"
Leila LaskuprinttiLeila Laskuprintti streetaddressstreetaddress postofficepostoffice
70460 KUOPIO70460 KUOPIOPyynpolku 1Pyynpolku 1
ElementElementgetTagNamegetTagNamegetAttributeNode(name)getAttributeNode(name)setAttributeNode(attr)setAttributeNode(attr)removeAttribute(name)removeAttribute(name)getElementsByTagName(name)getElementsByTagName(name)hasAttribute(name)hasAttribute(name)
NodeNode
DocumentDocument
ElementElement
NamedNodeMapNamedNodeMap
TextText
54
Additional Core Interfacesto handle ordered lists of nodes: NodeList
e.g. from Node.childNodes or Element.getElementsByTagName("name")
all descendant elements of type "name" in document order
to access unordered sets of nodes by name: NamedNodeMap
e.g. from Node.attributes
NodeLists and NamedNodeMaps are "live":changes to the document structure reflected to their contents
55
Object Creation in DOM
Each DOM object X lives in the context of a Document: X.ownerDocumentObjects implementing interface Y are created by factory methods
D.createY(…) ,where D is a Document object. E.g: createElement("A"), createAttribute("href"), createTextNode("Hello!")
Creation and persistent saving of Documents left to be specified by implementations
56
The main routine for BuildXml
public static void main(String args[]){ if (args.length > 0) {
String fileName = args[0]; BuildXml buildXml = new
BuildXml(fileName); } else {
System.err.println("Give filename as argument");
};} // main
57
JavaScriptWhat is JavaScript?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language A JavaScript consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license
58
What can a JavaScript Do? JavaScript gives HTML designers a programming tool
HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
59
JavaScript can be used to detect the visitor's browser A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
JavaScript can be used to create cookies A JavaScript can be used to store and retrieve information on the visitor's computer
JavaScript can read and write HTML elements A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
60
HTML Node Hierarchy
61
The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:
A) Opening or popping up a new window with programmatic control over the size, position and 'look' of the new window (i.e. whether the menus, toolbars, etc. are visible). B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server.
C) Changing images as the mouse cursor moves over them: This effect is often used to draw the user's attention to important links displayed as graphical elements.
How Javascript Interact With HTML DOM
62
Javascript Objects
Object Description Window Represents a browser window. A that is created
automatically with every instance of a <body> or <frameset> tag
Navigator Contains information about the client's browser
Screen Contains information about the client's display screen
Location Contains information about the current URL
History Contains the visited URLs in the browser window
63
HTML DOM Objects
Object DescriptionAnchor Represents an <a> element
Document Represents the entire HTML document and can be used to access all elements in a page.
Frame/ frameset Represents a <frame>/<frameset> element
Image Represents an <img> element
Event Represents the state of an event
Form Represents a <form> element
Option / Select Represent an <option> element / selection list in an HTML document.
Table, TableHeader, TableRow
Represent a <table>, <td> and <tr> element.
64
Adding in a new element
var link = document.createElement('a'); link.setAttribute('href', 'mypage.htm');
65
locating a slot in the document by location:
document.childNodes[1].childNodes[0] Find the main document element (HTML), and
find its second child (BODY), then look for its first child (DIV)
by ID: document.getElementById('myDiv').appendChild(txt);
66
Hiding an element
document.childNodes[1].childNodes[1].childNodes[0].style.display = "none";
67
Loading an XML document object into the parser <script language="JavaScript">
var xmlDoc = new
ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note.xml")
// ....... processing the document goes here
</script>
68
Manually loading XML into the parser <script language="JavaScript">
// load up variable var with some xml
var text="<note>"
text=text+"<to>John</to><from>Robert</from>"
text=text+"<heading>Reminder</heading>"
text=text+"<body>Don't forget your homework!</body>"
text=text+"</note>" // now create the DO
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.loadXML(text)
// ....... process the document
</script>
69
parseError object
document.write(xmlDoc.parseError.property) errorCode: Returns a long integer error code reason: Returns a string explaining the reason for the
error line: Returns a long integer representing the line number
for the error linePos: Returns a long integer representing the line
position for the error srcText: Returns a string containing the line that caused
the error url: Returns the url pointing the loaded document filePos: Returns a long integer file position of the error
70
Traversing nodes
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note.xml")
for each x in xmlDoc.documentElement.childNodes
document.write(x.nodename)
document.write(": ")
document.write(x.text)
next
71
Calling XML nodes by name
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note.xml")
document.write(xmlDoc.getElementsByTagName("from").item(0).tex
t)
Top Related