Presentation is loading. Please wait.

Presentation is loading. Please wait.

The JavaScript Environment

Similar presentations


Presentation on theme: "The JavaScript Environment"— Presentation transcript:

1 The JavaScript Environment
Concept: JavaScript lives within the browser and is presented a series of objects that it can manipulate to: Construct the user interface Add interactivity to content in a displayed window Create and manipulate additional windows Browsers present to JavaScript Browser Object Model of HTML tags and attributes Window/Document Model of browser objects JavaScript can find, manipulate, delete, insert HTML tags and attributes.

2 New HTML 5 - Tags Purpose: To make the web pages more semantic friendly

3 Linking HTML to JavaScript
Obtrusive <input type=“button” onclick=“JavaScript:jsFunction();” > or <script type=“text/JavaScript> // javascript code </script> Unobtrusive <script src=“jsFile.js” ></script> Putting script tags immediately before </html> will not slow down page loading and rendering Utilize the <noscript> tag for clients disabling JavaScript

4 Browser Object Model Next Slide HTML 5 also specifies a device object

5 Document Model Arrays of various kinds of objects. Netscape introduced this legacy structure early on. For Mobile Technology, avoid using these arrays

6 Window Methods & Properties
Expose Window object Partial Output window  window navigator  navigator document  document InstallTrigger  InstallTrigger str  str property  property console  console getInterface  getInterface sessionStorage  sessionStorage globalStorage  globalStorage localStorage  localStorage getComputedStyle  getComputedStyle dispatchEvent  dispatchEvent removeEventListener  removeEventListener addEventListener  addEventListener name  name parent  parent top  top <script type="text/javascript"> var str; for (var property in window) { str = window.property; document.write(property +"  <em>" + str +"</em><br />"); } </script>

7 Key Window Object Methods/Properties
Key Methods Key Properties alert, confirm, prompt setInterval, clearInterval setTimeout, clearTimeout open, close, focus scrollTo frames[], length navigator history location screen document parent, top, self, window Name // window name Status // Status bar Note: When referring to the window object we don’t need dot notation because window is the default. For example: window.alert(“hello”) and alert(“hello”) both work.

8 Opening & Closing Popup Windows
<html><head><title>Windows</title></head><body> <script type="text/javascript"> var win; function makeWindow() { win = window.open("bear.jpg", "bear", "width=300,height=300,resizable=yes,scrollbars=yes"); win.focus(); } function closeWindow() { win.close(); } </script> </head><body> <a href="JavaScript:makeWindow();">Bear picture</a> <a href ="JavaScript:closeWindow();">Close window</a> </body></html> Note: moveTo(x,y), moveBy(x,y), resizeTo(width,height) are additional methods

9 Limited Thread Processing
Note: Thread-based functions block the browser when it gets control One time Execute a function in time milliseconds var timeObject = setTimeout( function, time); Cancel: clearTimeout(timeObject); Example: Window resize events repeatedly fire, but we want to respond once. The listener cancel and reissues setTimeout each time. Repeated times Repeatedly execute every time milliseconds var timeObject = setInterval( function, time); Cancel: var clearInterval(timeObject); Example: Animation where a particular HTML component is to repeatedly move or rotate. Example: Scrollable messages

10 Web Workers (HTML 5) var worker = new Worker("workerFile.js");
Purpose: Avoid single thread execution that blocks the browser var worker = new Worker("workerFile.js"); btn.addEventListener("click", function() { worker.postMessage(someTextToSendToWorker); }, false); } At some point: worker.terminate(); Worker.js file ( function{} { addEventListener("message", function(e) { /* code here */ // In a loop using AJAX or setInterval postMessage(textData); // Send to main JavaScript }, false); })(); // Note: the main thread adds a “message” handler to respond

11 The scrollTo method scrollTo(x, y); Example of use:
ACORNS hear and respond and story book lessons play audio, and as the audio plays, the lesson highlights the word that displays and insures that it is visible to the user. ACORNS code I actually uses another method that is part of HTML tag objects called, scrollIntoView(). The scrollIntoView() method then calls scrollTo(). Calling scrollIntoView is easier because it finds the x,y position of the word corresponds to the playing audio.

12 Frames[] array Frames are windows within the primary window
Note: We’ll not say much about frames, because they should be avoided on mobile devices Frames are windows within the primary window These are created using HTML <frame>, <iframe> tags. The <frame> tag is antiquated and is poor web-design Pages are cumbersome to set up and maintain For a page with four frames, five web pages are required The <iframe> tag is better, but not for mobile devices It is not universally supported Limited display space causes design problems Automatic portrait/landscape zooming and resizing causes difficulties

13 Navigator Object Methods and Properties
Partial Output Shown Purpose: Describe the Browser appCodeName   Mozilla appName   Netscape appVersion   5.0 (Windows) language   en-US mimeTypes   [object MimeTypeArray] platform   Win32 oscpu   Windows NT 5.1 vendor    vendorSub    product   Gecko productSub    plugins   [object PluginArray] securityPolicy    userAgent   Mozilla/5.0 (Windows NT 5.1; rv:5.0.1) Gecko/ Firefox/5.0.1 cookieEnabled   true <script type="text/javascript"> var str; for (var property in navigator) { str = navigator[property]; document.write(property +"  <em>" + str +"</em><br />"); } </script> Note: for/in loop is good for finding methods & properties in any object

14 Expose Browser Plugin List
Partial Output Shown <script type="text/javascript"> var len = navigator.plugins.length; for (var i=0; i<len; i++) { document.write( (i+1) + " " + navigator.plugins[i].name + "<br />" + navigator.plugins[i].filename + "<br />"); } </script> 1 Mozilla Default Plug-in npnul32.dll 2 Adobe Acrobat nppdf32.dll 3 Java Deployment Toolkit npdeployJava1.dll 4 QuickTime Plug-in 7.7 npqtplugin.dll 5 QuickTime Plug-in 7.7 npqtplugin2.dll 6 QuickTime Plug-in 7.7 npqtplugin3.dll 7 QuickTime Plug-in 7.7 npqtplugin4.dll

15 Expose MIME Types Supported
MIME: Data exchange formats Partial Output <script type="text/javascript"> var len = navigator.mimeTypes.length; var type, suffix, desc, enabled; for (var i=0; i<len; i++) { type = navigator.mimeTypes[i]; suffix = type.suffixes; desc = type.description; enabled = type.enabledPlugin; if (enabled && suffix.length==3) { document.write( desc + "," + suffix + "<br />"); } } </script> Acrobat Portable Document Format,pdf Acrobat Forms Data Format,fdf Acrobat XML Data Package,xdp Adobe FormFlow99 Data File,xfd SDP stream descriptor,sdp SDP stream descriptor,sdp QUALCOMM PureVoice audio,qcp GSM audio,gsm AMR audio,AMR CAF audio,caf AC3 audio,ac3 AC3 audio,ac3 SD video,sdv AMC media,amc MPEG-4 media,mp4

16 History Object Information pertaining to pages recently visited in this session Properties Methods Current: current document object Search: CGI string of the current document Next: URL of the next document Previous: URL of the eprevious document Length: Number of history document objects Go back one page back() Go forward one page forward() Go forward or back n pages go(n) Return URL of the nth item Item(n) Listeners for changing pages pushState, popState Note: window.onpopupstate listener can respond to pushstate and popstate events

17 The Screen Object Available space minus toolbars and scrollbars
Information about the size of the window display area ACORNS used this to accommodate any device display size Properties Available space minus toolbars and scrollbars availHeight, availWidth availTop, availLeft // Upper top/left position. Not IE or Opera browsers Total size of the screen width, height colorlDepth // bits per pixel

18 Document Object Properties/Methods
Key Methods bgColor, fgColor: deprecated The browser tab contents document.title = "Web page"; Last modified date alert(document.lastModified); Server rendering the page alert(document.domain); The page’s full URL alert(document.URL); getElementById("foo") getElementsByName("foo") getElementsByTagName("foo") getElementsByClassName("foo") elementFromPoint(x,y) clear(), open(), close() write(), writeln() createElement("foo") createTextNode("some text")

19 Creating/Retrieving Cookies
Creating a cookie Without an expiration date, the cookie will never be written Setting document.cookie appends, instead of simply assigning Example var cookie = "name=bob;expires="; var expDate = new Date(); expDate.setDate(expDate.getDate() + EXP_DAYS); cookie += expDate.toGMTString(); document.cookie = cookie; Retrieving a cookie: document.cookie contains the cookies separated by ";" var pairs = document.cookie.split(";"); for (var i=0; i<pairs.length; i++) { console.log("Name =" + pairs[i].split("=")[0] + "value = " + unescape( pairs[i].split("=")[1] ); }

20 Local Storage (HTML 5) Local Storage (2-10mb, cleared by user action)
localStorage.setItem(key, data); localStorage.getItem(key); localStorage.removeItem(key); Session Storage (Deleted when browser exits) sessionStorage.setItem(key, data); sessionStorage.getItem(key); sessionStorage.removeItem(key); Notes Only strings can be stored JSON.stringify(object) or JSON.parse(data) to retrieve an object if (typeof(localStorage) != undefined) // determine if supported

21 The Dom consists of Element Nodes: The objects (nodes) in the DOM tree
Methods: Contained in element objects Properties that are contained in all DOM elements id: identifier. No two elements should have the same id className: CSS class name innerHTML: (now part of HTML 5 standards) Attributes Nodes: The name to the left of the equal sign of most tag parameters. Name and values contained in the attribute nodes Methods: setAttribute() and getAttribute() Caution: Don’t use getAttribute() or setAttribute for id and name properties. Don’t use element.attributeName for attributes in the attribute nodes

22 <html> <head> <title> My Title </title> </head> <body> <a href=x.html> My link </a> <h1> My header </h1> </body> </html> Document Object Model An API defining the logical tree structure of well-formed, valid HTML/XML documents enabling access and manipulation Note: Some browsers create unexpected whitespace text nodes Solution: Use a utility to remove whitespace from web pages

23 Functionality Search for an element by its identifier (id)
Search for all elements by its name Search for all occurrences of a particular tag Navigate through the DOM Access parent, child, sibling elements Insert/remove elements to/form the DOM Modify the content of parts of the DOM Change an element’s styles and properties Call methods specific to particular elements Add listeners to respond to user events

24 Properties/Methods of all DOM Elements
General: id, style, title, tabIndex ReadOnly : nodeName, localName, className (before HTML 5) List of attributes: attributes[] Cloning: cloneNode() Navigation aids: childNodes[], firstChild, lastChild, nextSibling, previousSibling, parentNode, innerHTML Size minus borders (client*) client + Height, Width, Top, Left Total size (offset*) offset + Height, Width, Top, Left View within scroll area (scroll*) scroll + Height, Width, Left, Top Searching getElementById(id) getElementsByTagName(name) getElementsByClassName(name) getElementsByName(name) Editing the DOM appendChild(node), replaceChild(node) removeChild(node), insertBefore(node) Attributes: getAttribute(), setAttribute(att,value), removeAttribute(att), Create a copy: cloneNode(node) Focus for entry: focus(), blur() Trigger event: click() Note: The next slides are examples code snippets from ACORNS

25 Code Examples Remove all children
while (body.childNodes.length > 0) { body.removeChild( body.firstChild ); } Find element by name starting from a particular node findElementByName = function(node, name) { if (node.name == name) return node; if (node.getAttribute && node.getAttribute("name") == name) return node; if (!node.hasChildNodes()) return false; var element; for (var c=0; c<node.childNodes.length; c++) { element = this.findElementByName(node.childNodes[c], name); if (element) return element; } return false;

26 Find x,y Position of a Node
this.getPosition = function(id) { var tag = id, x = 0, y = 0; if (typeof id == "string") tag=document.getElementById(id); while( tag && !isNaN( tag.offsetLeft ) && !isNaN( tag.offsetTop ) ) { x += tag.offsetLeft - tag.scrollLeft; y += tag.offsetTop - tag.scrollTop; tag = tag.offsetParent; } return { top: y, left: x }; Traverse up the DOM adding offsets till we get to the top element

27 Retrieving a Node’s Attributes
/** Function to create a picture object **/ var getPicture = function(acorns, node) { var angle = node.getAttribute("angle"); var type = node.getAttribute("scale"); var src = node.getAttribute("src"); var value = node.getAttribute("value“,); return new Picture(acorns, src, type, angle, value); } Note: Attributes are in a separate DOM node from an element node. Some attributes are not in this object on all browsers (example: name, id). Node.id or node.name should be used if this is the case to access these attributes

28 Examples of using innerHTML
Maintaining student scores for various ACORNS Lessons div.innerHTML = "0<br>of<br>0"; var score = resultPanel.innerHTML.toLowerCase().split("<br>"); resultPanel.innerHTML = score[0] + "<br>of<br>" + score[2]; A more complex example: if Java-based audio recording enabled if (recordEnabled && acorns.system.isExplorer()) { div = document.createElement("div"); div.innerHTML = '<object classid="clsid:8AD9C E-11D1-B3E F499D93" ' +'codebase=" + 'height="0" width="0" id="AudioHandler" name="AudioHandler"> ' + '<param name="code" value="org.acorns.AudioHandler" />' + '<param name="archive" value="DesktopAcornsAudioExtension.jar" />' + '<param name="mayscript" value="true" />’+'<param name="scriptable" value="true”/>' + '<strong>This browser does not have a Java Plug-in.</strong>’+ '</object> '; body.appendChild(div); } Note: InnerHTML didn’t parse and create elements. In HTML5, apparently It now does.

29 Using innerHTML Prior to HTML5 HTML 5
innerHTML was universally supported, but not W3C standard Some browsers did not parse and add nested tags to the DOM HTML 5 Part of the HTML 5 standard and is reasonably fast Supporting browsers parse and add nested tags to the DOM The following now works, assuming: <body id="data"> </body> <script type="text/javascript"> var data = document.getElementById("data") data.innerHTML = '<h2 id="header">header</h2> var header = document.getElementById("header"); header.innerHTML = "new header"; </script>

30 Search by Tag Name Note: Internet Explorer 8 does not support the HTML5 audio tag It does support the bgsound tag, however This code removes story book lesson options that Explorer can’t handle var tips = ["replay the last part of the recording", "pause“ , "stop to start over", "play audio" ]; var controls = [ "replay", "pause", "stop", "play" ]; var players = document.getElementsByTagName("bgsound"); if (players && players.length>0) { controls.splice(0,2); tips.splice(0,2); }

31 Removing Elements by Name
var elements = document.getElementsByName ("pictureAndSounds"); for (var e = elements.length - 1; e>=0; e--) { elements[e].parentNode.removeChild (elements[e] ); }

32 Modifying CSS Advantage: Removes CSS code in JavaScript facilitating progressive enhancement Methods var element = document.querySelector("#header"); var element = document.querySelector(".header"); var matches = document.querySelectorAll(".note, div.alert"); var matches = document.querySelectorAll("p"); var matches = document.querySelectorAll('area[href], a[href]'); var element = document.querySelector("p[class]"); var element = document.getElementsByClassName("className"); [] = find all elements with the specified attribute set # refers to id value, . Refers to name value

33 Modifying an Elements Class
To set a CSS classes for an element: document.getElementById("Element").className = "C1"; To set more than one CSS class into an element: document.getElementById("Element").className = "C1 C2"; To add an additional class to an element: document.getElementById("Element").className += " C1"; To remove a class from an element: var tag = document.getElementById("Element").className; tag.className.replace(/\bMyClass\b/, "");

34 Adding a Bunch of Text Nodes
var lines = text.split("\n"), words, span, wordCount = 0; for (var lineNo=0; lineNo<lines.length; lineNo++) { words = lines[lineNo].split(" "); for (var wordNo=0; wordNo<words.length; wordNo++) { if (wordNo==0 && lineNo!=0) textDisplay.appendChild(document.createElement("br")); span = document.createElement("span"); span.id = "" + wordCount++; span.innerHTML = words[wordNo]; textDisplay.appendChild(span); if (wordNo< words.length - 1) textDisplay.appendChild(document.createTextNode(" ")); }


Download ppt "The JavaScript Environment"

Similar presentations


Ads by Google