1 / 34

The JavaScript Environment

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

ramona
Download Presentation

The JavaScript Environment

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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  windownavigator  navigatordocument  documentInstallTriggerInstallTriggerstrstrproperty  propertyconsole  consolegetInterfacegetInterfacesessionStoragesessionStorageglobalStorageglobalStoragelocalStoragelocalStoragegetComputedStylegetComputedStyledispatchEventdispatchEventremoveEventListenerremoveEventListeneraddEventListeneraddEventListenername  nameparent  parenttop  top <script type="text/javascript"> var str; for (var property in window) { str = window.property; document.write(property +"&nbsp;&nbsp;<em>" + str +"</em><br />"); } </script>

  7. Key Window Object Methods/Properties Key Methods Key Properties frames[], length navigator history location screen document parent, top, self, window Name // window name Status // Status bar • alert, confirm, prompt • setInterval, clearInterval • setTimeout, clearTimeout • open, close, focus • scrollTo 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 millisecondsvar 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 millisecondsvar 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) 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 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 <script type="text/javascript"> var str; for (var property in navigator) { str = navigator[property]; document.write(property +"&nbsp;&nbsp;<em>" + str +"</em><br />"); } </script> appCodeName   MozillaappName   NetscapeappVersion   5.0 (Windows)language   en-USmimeTypes   [object MimeTypeArray]platform   Win32oscpu   Windows NT 5.1vendor   vendorSub   product   GeckoproductSub   20100101plugins   [object PluginArray]securityPolicy   userAgent   Mozilla/5.0 (Windows NT 5.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1cookieEnabled   true 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.dll2 Adobe Acrobatnppdf32.dll3 Java Deployment Toolkit 6.0.270.7npdeployJava1.dll4 QuickTime Plug-in 7.7npqtplugin.dll5 QuickTime Plug-in 7.7npqtplugin2.dll6 QuickTime Plug-in 7.7npqtplugin3.dll7 QuickTime Plug-in 7.7npqtplugin4.dll

  15. Expose MIME Types Supported MIME: Data exchange formats Partial Output Acrobat Portable Document Format,pdfAcrobat Forms Data Format,fdfAcrobat XML Data Package,xdpAdobe FormFlow99 Data File,xfdSDP stream descriptor,sdpSDP stream descriptor,sdpQUALCOMM PureVoice audio,qcpGSM audio,gsmAMR audio,AMRCAF audio,cafAC3 audio,ac3AC3 audio,ac3SD video,sdvAMC media,amcMPEG-4 media,mp4 <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>

  16. History Object Information pertaining to pages recently visited in this session Properties Methods Go back one pageback() Go forward one pageforward() Go forward or back n pagesgo(n) Return URL of the nth itemItem(n) Listeners for changing pagespushState, popState • 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 Note:window.onpopupstate listener can respond to pushstate and popstate events

  17. The Screen Object 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 Properties Key Methods getElementById("foo") getElementsByName("foo") getElementsByTagName("foo") getElementsByClassName("foo") elementFromPoint(x,y) clear(), open(), close() write(), writeln() createElement("foo") createTextNode("some text") • bgColor, fgColor: deprecated • The browser tab contentsdocument.title = "Web page"; • Last modified datealert(document.lastModified); • Server rendering the pagealert(document.domain); • The page’s full URLalert(document.URL);

  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="; varexpDate = new Date(); expDate.setDate(expDate.getDate() + EXP_DAYS); cookie += expDate.toGMTString(); document.cookie = cookie; • Retrieving a cookie: document.cookie contains the cookies separated by ";" varpairs = document.cookie.split(";"); for (vari=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. Document Object Model An API defining the logical tree structure of well-formed, valid HTML/XML documents enabling access and manipulation <html> <head> <title> My Title </title> </head> <body> <a href=x.html> My link </a> <h1> My header </h1> </body> </html> 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 Properties Methods SearchinggetElementById(id)getElementsByTagName(name) getElementsByClassName(name)getElementsByName(name) Editing the DOMappendChild(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() • 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 Note: The next slides are examples code snippets from ACORNS

  25. Code Examples Remove all children 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; } while (body.childNodes.length > 0) { body.removeChild( body.firstChild ); }

  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:8AD9C840-044E-11D1-B3E9-00805F499D93" ' +'codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0-windows-i586.cab"' + '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 • 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(" ")); }

More Related