the javascript environment concept: javascript lives within the browser and is presented a series of...
Post on 15-Jan-2016
220 views
TRANSCRIPT
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.
New HTML 5 - Tags
Purpose: To make the web pages more semantic friendly
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
Browser Object Model
HTML 5 also specifies a device object
NextSlide
Document ModelArrays of various kinds of objects. Netscape introduced this legacy structure early on. For Mobile Technology, avoid using these arrays
Window Methods & PropertiesExpose Window object
<script type="text/javascript">var str;for (var property in window){
str = window.property;document.write(property
+" <em>"+ str+"</em><br />");
}</script>
Partial Outputwindow windownavigator navigatordocument documentInstallTrigger InstallTriggerstr strproperty propertyconsole consolegetInterface getInterfacesessionStorage sessionStorageglobalStorage globalStoragelocalStorage localStoragegetComputedStyle getComputedStyledispatchEvent dispatchEventremoveEventListener removeEventListeneraddEventListener addEventListenername nameparent parenttop top
Key Window Object Methods/Properties
Key Methods• alert, confirm, prompt• setInterval, clearInterval• setTimeout, clearTimeout• open, close, focus• scrollTo
Key Properties• 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.
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
Limited Thread Processing
• 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
Note: Thread-based functions block the browser when it gets control
Web Workers (HTML 5)
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
Purpose: Avoid single thread execution that blocks the browser
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.
Frames[] array
• 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
Note: We’ll not say much about frames, because they should be avoided on mobile devices
Navigator Object Methods and Properties
<script type="text/javascript">var str;for (var property in navigator){
str = navigator[property];document.write(property
+" <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
Partial Output ShownPurpose: Describe the Browser
Note: for/in loop is good for findingmethods & properties in any object
Expose Browser Plugin List
<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-innpnul32.dll
2 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
Partial Output Shown
Expose MIME Types Supported
MIME: Data exchange formats
<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>
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
History Object
Properties• 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
Methods• 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
Information pertaining to pages recently visited in this session
Note: window.onpopupstate listener can respond to pushstate and popstate events
The Screen Object
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
Information about the size of the window display areaACORNS used this to accommodate any device display size
Document Object Properties/Methods
Properties• bgColor, fgColor: deprecated• The browser tab contents
document.title = "Web page";• Last modified date
alert(document.lastModified);
• Server rendering the pagealert(document.domain);
• The page’s full URLalert(document.URL);
Key Methods• getElementById("foo")• getElementsByName("foo")• getElementsByTagName("foo")• getElementsByClassName("foo")• elementFromPoint(x,y)• clear(), open(), close()• write(), writeln()• createElement("foo")• createTextNode("some text")
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] ); }
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
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
Document Object ModelAn API defining the logical tree structure of well-formed, valid HTML/XML documents enabling access and manipulation
Note: Some browsers create unexpected whitespace text nodesSolution: Use a utility to remove whitespace from web pages
<html> <head> <title> My Title </title> </head> <body> <a href=x.html> My link </a> <h1> My header </h1> </body></html>
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
Properties/Methods of all DOM ElementsProperties
• 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
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()
Note: The next slides are examples code snippets from ACORNS
Code ExamplesRemove all childrenwhile (body.childNodes.length > 0) { body.removeChild( body.firstChild ); }
Find element by name starting from a particular nodefindElementByName = 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;}
Find x,y Position of a Nodethis.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
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
Examples of using innerHTML1. Maintaining student scores for various ACORNS Lessons
a. div.innerHTML = "0<br>of<br>0";b. var score = resultPanel.innerHTML.toLowerCase().split("<br>");c. resultPanel.innerHTML = score[0] + "<br>of<br>" + score[2];
2. A more complex example: if Java-based audio recording enabledif (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.
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>
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); }
Removing Elements by Name
var elements = document.getElementsByName("pictureAndSounds");
for (var e = elements.length - 1; e>=0; e--){
elements[e].parentNode.removeChild(elements[e] );
}
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
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/, "");
Adding a Bunch of Text Nodesvar 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(" "));}