Javascript
Upcoming SlideShare
Loading in...5
×
 

Javascript

on

  • 4,135 views

Introduction to javascript

Introduction to javascript

Statistics

Views

Total Views
4,135
Views on SlideShare
4,124
Embed Views
11

Actions

Likes
2
Downloads
177
Comments
1

2 Embeds 11

http://www.futureforyou.biz 9
http://theexamtime.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • A very good presentation on Javascript. It would be very useful for those who are beginners in web programming.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Javascript Javascript Presentation Transcript

  • JavaScript CCSS TEAM: Eng. Musavir Iftekhar Bhatti
  • 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.
  • 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 1 st time. User can used entered value for welcome page.
  • Java VS JavaScript Code integrated with, and embedded in, HTML. Applets distinct from HTML (accessed from HTML pages). Variable data types not declared (loose typing). Variable data types must be declared (strong typing). Interpreted (not compiled) by client. Compiled on server before execution on client. Much smaller and simpler set of commands . Much larger and advanced set of commands. Netscape Sun Microsystems JavaScript Java
  • 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
    • <html>
    • <body>
    • <script type=&quot;text/javascript&quot;>
    • document.write(&quot;HelloWorld!&quot;)
    • </script>
    • </body>
    • </html>
    • The above code will produce this output on the HTML page.
    • HelloWorld!!
    • To insert a JavaScript into an HTML page, we use the <script> tag.
    • The <script type=&quot;text/javascript&quot;> 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.
    • 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.
    • <html>
    • <body>
    • <script type=&quot;text/javascript&quot;>
    • ...
    • </script>
    • </body>
    • </html>
    • 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(&quot;Hello World!&quot;) command as pure text, and just write the entire line on the page.
    • This will be the output
    document.write(&quot;Hello World!&quot;)
    • 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>
  • 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.
  • A simple example for external scripts
    • Save as main.html
    • Save as hello.js
    <html> <head> <body> <script language=&quot;javascript&quot; type=&quot;text/javascript&quot; src=&quot;hello.js&quot;> </body> </head> </script> var hello = 'Hello World'; document.write(hello);
  • Output
    • Hello World!
  • <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.
  • Example
    • <noscript>
    • Your browser does not support JavaScript!
    • </noscript>
    • <html>
    • <head>
    • <body> ... ... <script type=&quot;text/javascript&quot;> <!-- document.write(&quot;Hello World!&quot;) //--> </script> <noscript>
    • Your browser does not support JavaScript!
    • </noscript> ... ... </body>
    • </head>
    • </html>
  • 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.
  • 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.
  • 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=&quot;text/javascript&quot;>
    • var txt=&quot;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 ! )
  • 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=&quot;text/javascript&quot;>
    • var str=&quot;Hello world!&quot;
    • document.write(str.toUpperCase())
    • </script>
    • The output of the code above will be:
    • HELLO WORLD!
  • The most commonly used JavaScript objects Focus, blur, select defaultValue, name, type, value Text Submit, reset Action, elements, encoding, FileUpload, method, name, target Form None Border, complete, heigth, hspace, lowwsrc, vspace, width Image Clear, close, open, write, writeln alinkColor, anchors, applets, ares, bgColor, cookie, fgColor, forms, images, lastModified, linkColor, links, location, referrer, title, vlinkColor Documents javaEnabled appCodeName, appName, appVersion, mimeTypes, plugins, userAgents Navigator Back Length, forward, go History Reload, replace Hash, host, hostname, href, pathname, por, protocol, search Location Alert, blur, close, confirm, focus, open, prompt, clearTimeout, setTimeout defaultStatus, frames, opener, parent, scroll, self, status, top, window Frame Alert, blur ,close, confirm, focus, open, prompt, clearTimeout, setTimeout defaultStatus, frames, opener, parent, scroll, self, status, top, window Window Methods Properties Object
  • The most commonly used Built-in JavaScript Objects Methods Properties Objects Anchor, big, blink, bold, charAt, fixed, fontColor, fontSize, indexOf, italics, lastIndexOf, link, small, split, strike, sub, substring, sup, toLowerCase,toUpperCase Length, Prototype String getDate, getDay, getHours, getMinutes, getMonth, getSeconds, getTime, getTimeZoneoffset, getYear, parse, prototype, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC None Date Join, reverse, sort xx Length Array
  • Built-in JavaScript Objects
    • String Object
    • Date Object
    • Array Object
    • Math Object
    • Boolean Object
    • 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=&quot;text/javascript&quot;>
    • var txt=&quot;Hello World!”
    • document.write(txt.length)
    • </script>
    • The above code will result in following output:
    • 12
    Built-in JavaScript Objects - String
    • 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=&quot;text/javascript&quot;>
    • document.write(Date())
    • </script>
    • The output will be:
    • Mon Nov 05 15:51:51 2007
    Built-in JavaScript Objects - Date
    • This 2 nd example shows how to use getTime() method to calculate years since 1970:
    • <script type=&quot;text/javascript&quot;>
    • var minutes = 1000*60
    • var hours = minutes*60
    • var days = hours*24
    • var years = days*365
    • var d = new Date()
    • var t = d.getTime()
    • var y = t/years
    • document.write(&quot;It's been: &quot; + y + &quot; years since 1970/01/01!&quot;)
    • </script>
    • The output will be:
    • It's been: 37.86941401639396 years since 1970/01/01!
    Built-in JavaScript Objects - Date
    • 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&quot;
    • mycars[1]=&quot;Volvo&quot;
    • mycars[2]=&quot;BMW&quot;
    • OR
    • var mycars=new Array(&quot;Saab&quot;,&quot;Volvo&quot;,&quot;BMW&quot;)
    Built-in JavaScript Objects - Array
    • 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
    • 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
    • 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
    • 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
    • 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
    • If the Boolean object has no initial value or if it is 0, -0, null, &quot;&quot;, false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string &quot;false&quot;).
    • 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(&quot;&quot;)
    • 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(&quot;true&quot;)
    • var myBoolean=new Boolean(&quot;false&quot;)
    • var myBoolean=new Boolean(&quot;Richard&quot;)
    Built-in JavaScript Objects - Boolean
  • How to create an object?
    • Create a direct instance of an object
    • Create template of an object
  • Object A bird (object) Fly () name age EyeColor Eat() Drink() METHODS PROPERTIES
    • 1. Direct Instance
    • Add few properties to the bird
    • BirdObj=new Object()
    • BirdObj.name=“MorningBird“
    • BirdObj.age=2
    • BirdObj.eyecolor=“green&quot;
    • Add methods to the bird BirdObj.fly = fly
    • BirdObj.eat = eat
    • BirfObj.Breath = breath
    • 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”)
    • 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”)
  • 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.”
  • 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
  • Object-based document modelling
    • Object model covers
      • structure of a document
      • behaviour of a document and its constituent objects
    • DOM defines
      • interfaces and objects for representing and manipulating documents
      • semantics of these interfaces
      • relationships between interfaces and objects
  • 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
  • <invoice> <invoicepage form=&quot;00&quot; type=&quot;estimatedbill&quot;> <addressee> <addressdata> <name>Leila Laskuprintti</name> <address> <streetaddress>Pyynpolku 1 </streetaddress> <postoffice>70460 KUOPIO </postoffice> </address> </addressdata> </addressee> ... XML DOM structure model invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Document Element NamedNodeMap Text
  • HTML DOM structure model The DOM presents an HTML document as a tree-structure (a node tree), with elements, attributes, and text.
    • 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
  • Structure of DOM Level 1
    • Two 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 documents
    • Level 1 intentionally limited to representation and manipulation of document structure and content
      • document instance only; no access to the contents of a DTD
  • DOM Level 2
      • support for namespaces
      • accessing elements by ID attribute values
      • optional features
        • interfaces to document views and stylesheets
        • an 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)
    • Consists of 6 different specifications:
    • DOM Level 3 Core;
    • DOM Level 3 Load and Save
    • DOM Level 3 XPath;
    • DOM Level 3 Views and Formatting;
    • DOM Level 3 Requirements; and
    • DOM Level 3 Validation, which further enhances the DOM
    DOM Level 3
  • Core Interfaces: Node & its variants Node Comment DocumentFragment Attr Text Element CDATASection ProcessingInstruction CharacterData Entity DocumentType Notation EntityReference “ Extended interfaces” Document
  • DOM interfaces: Node invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Node getNodeType getNodeValue getOwnerDocument getParentNode hasChildNodes getChildNodes getFirstChild getLastChild getPreviousSibling getNextSibling hasAttributes getAttributes appendChild(newChild) insertBefore(newChild,refChild) replaceChild(newChild,oldChild) removeChild(oldChild) Document Element NamedNodeMap Text
  • invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Document getDocumentElement createAttribute(name) createElement(tagName) createTextNode(data) getDocType() getElementById(IdVal) Node DOM interfaces: Document Document Element NamedNodeMap Text
  • DOM interfaces: Element invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Element getTagName getAttributeNode(name) setAttributeNode(attr) removeAttribute(name) getElementsByTagName(name) hasAttribute(name) Node Document Element NamedNodeMap Text
  • Additional Core Interfaces
    • to handle ordered lists of nodes: NodeList
      • e.g. from Node.childNodes or Element.getElementsByTagName(&quot;name&quot;)
        • all descendant elements of type &quot;name&quot; in document order
    • to access unordered sets of nodes by name: NamedNodeMap
      • e.g. from Node.attributes
    • NodeList s and NamedNodeMap s are &quot;live&quot;:
      • changes to the document structure reflected to their contents
  • Object Creation in DOM
    • Each DOM object X lives in the context of a Document: X .ownerDocument
    • Objects implementing interface Y are created by factory methods D .create Y (…) , where D is a Document object. E.g:
      • createElement(&quot;A&quot;), createAttribute(&quot;href&quot;), createTextNode(&quot;Hello!&quot;)
    • Creation and persistent saving of Document s left to be specified by implementations
  • 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( &quot;Give filename as argument&quot;);
    • };
    • } // main
  • JavaScript
    • What 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
  • 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 &quot;snippets&quot; of code into their HTML pages
    • JavaScript can put dynamic text into an HTML page
    • A JavaScript statement like this: document.write(&quot;<h1>&quot; + name + &quot;</h1>&quot;) 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
    • 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
  • HTML Node Hierarchy
  • How Javascript Interact With HTML DOM 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.
  • Javascript Objects Description Object Contains the visited URLs in the browser window History Contains information about the current URL Location Contains information about the client's display screen Screen Contains information about the client's browser Navigator Represents a browser window. A that is created automatically with every instance of a <body> or <frameset> tag Window
  • HTML DOM Objects Represent an <option> element / selection list in an HTML document. Option / Select Represents an <a> element Anchor Represents a <form> element Form Represents the state of an event Event Represents an <img> element Image Represents a <frame>/<frameset> element Frame / frameset Represent a <table>, <td> and <tr> element. Table, TableHeader, TableRow Represents the entire HTML document and can be used to access all elements in a page. Document Description Object
  • Adding in a new element
    • var link = document.createElement('a'); link.setAttribute('href', 'mypage.htm');
  • 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);
  • Hiding an element
    • document.childNodes[1].childNodes[1].childNodes[0].style.display = &quot;none&quot;;
  • Loading an XML document object into the parser
    • <script language=&quot;JavaScript&quot;> var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) // ....... processing the document goes here </script>
  • Manually loading XML into the parser
    • <script language=&quot;JavaScript&quot;> // load up variable var with some xml var text=&quot;<note>&quot; text=text+&quot;<to>John</to><from>Robert</from>&quot; text=text+&quot;<heading>Reminder</heading>&quot; text=text+&quot;<body>Don't forget your homework!</body>&quot; text=text+&quot;</note>&quot; // now create the DO var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc. loadXML (text) // ....... process the document </script>
  • 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
  • Traversing nodes
    • set xmlDoc=CreateObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) for each x in xmlDoc.documentElement.childNodes document.write(x.nodename) document.write(&quot;: &quot;) document.write(x.text) next
  • Calling XML nodes by name
    • var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) document.write(xmlDoc.getElementsByTagName(&quot;from&quot;).item(0).text)