JAVASCRIPT - Cs.toronto.edu

Transcription

JAVASCRIPT

Overview2 Introduction to JavaScriptThe JavaScript LanguageGlobal DOM Objects (Browser)The DOM Tree modelUnobtrusive JavaScript

3Introduction to JavaScript

Client Side Scripting4

Why use client-side programming?5Any server side programming language allows us tocreate dynamic web pages. Why also use client-sidescripting? client-side scripting (JavaScript) benefits: usability:can modify a page without having to postback to the server (faster UI) efficiency: can make small, quick changes to pagewithout waiting for server event-driven: can respond to user actions like clicks andkey pressesCSC309

Why use Server-side programming?6 server-side programming benefits: security:has access to server's private data; client can'tsee source code compatibility: not subject to browser compatibilityissues power: can write files, open connections to servers,connect to databases, .CSC309

What is Javascript?7 a lightweight programming language ("scriptinglanguage") usedto make web pages interactive insert dynamic text into HTML (ex: a date) react to events (ex: user clicks on a button) get information about a user's computer (ex: browsertype) perform calculations on user's computer (ex: formvalidation)CSC309

What is Javascript?8 a web standard (but not supported identically byall browsers)NOT related to Java other than by name and somesyntactic similaritiesCSC309

Javascript vs Java9 interpreted, not compiledmore relaxed syntax and rules fewerand "looser" data types variables don't need to be declared errors often silent (few exceptions) key construct is the function rather than the classcontained within a web page and integrates with itsHTML/CSS contentCSC309

Linking to a JavaScript file: script10 script src "filename" type "text/javascript" /script HTML script tag should be placed in HTML page's headscript code is stored in a separate .js fileJS code can be placed directly in the HTML file'sbody or head (like CSS) butthis is bad style (should separate content,presentation, and behavior)CSC309

Event-driven programming11CSC309

A JavaScript statement: alert12alert("IE6 detected."); JSa JS command that pops up a dialog box with amessageCSC309

Event-driven programming13 you are used to programs that start with a mainmethod (or implicit main like in PHP)JavaScript programs instead wait for user actionscalled events and respond to themevent-driven programming: writing programs drivenby user eventsLet's write a page with a clickable button that popsup a "Hello, World" window.CSC309

Buttons14 button Click me! /button HTMLbutton's text appears inside tag; can also containimagesTo make a responsive button or other UI control:1.2.3.CSC309choose the control (e.g. button) and event (e.g. mouseclick) of interestwrite a JavaScript function to run when the eventoccursattach the function to the event on the control

JavaScript functions15function name() {statement ;statement ;.statement ;}function myFunction() {alert("Hello!");alert("How are you?");} JSJSthe above could be the contents of example.jslinked to our HTML pagestatements placed into functions can be evaluated inresponse to user events

Event handlers16 element attributes onclick "function();" .HTML button onclick "myFunction();" Click me! /button HTML JavaScript functions can be set as event handlers when you interact with the element, the function will executeonclick is just one of many event HTML attributesbut popping up an alert window is disruptive andannoying CSC309A better user experience would be to have the messageappear on the page.

Document Object Model (DOM)17 most JS code manipulateselements on an HTML pagewe can examine elements’ state(e.g. see whether a box is checked) we can change state (e.g. insertsome new text into a div) we can change styles (e.g. make aparagraph red)

DOM element objects18

Access element: document.getElementById19var name document.getElementById("id"); button onclick "changeText();" Click me! /button span id "output" replace me /span input id "textbox" type "text" / JSHTMLfunction changeText() {var span document.getElementById("output");var textBox olor "red";}CSC309JS

Access element: document.getElementById20 document.getElementById returns the DOM objectfor an element with a given idcan change the text inside most elements by settingthe innerHTML propertycan change the text in form controls by setting thevalue propertyCSC309

Change elem. style: element.style21AttributeProperty or style groundColorborder-top-widthborderTopWidthFont sizefontSizeFont famiyfontFamilyCSC309

Preetify22function changeText() {//grab or initialize text here}CSC309// font styles added by JS:textbox.style.fontSize "13pt";textbox.style.fontFamily "Comic Sans MS";textbox.style.color "red"; // or pink?JS

23The JavaScript LanguageCSC309

Variables24var name expression;var clientName "Connie Client";var age 32;var weight 127.4;JS JSvariables are declared with the var keyword (casesensitive)types are not specified, but JS does have types("loosely typed") Number, Boolean, String, Array, Object,Function, Null, Undefined canCSC309find out a variable's type by calling typeof

Number type25var enrollment 99;var medianGrade 2.8;var credits 5 4 (2 * 3); JSintegers and real numbers are the same type (no intvs. double)same operators: - * / % -- - * / % similar precedence to Javamany operators auto-convert types: "2" * 3 is 6CSC309

Comments (same as Java)26// single-line comment/* multi-line comment */ identical to Java's comment syntaxrecall: 4 comment syntaxes HTML: !-- comment -- CSS/JS/PHP: /* comment */ Java/JS/PHP: // comment PHP: # commentCSC309JS

Math object27var rand1to10 Math.floor(Math.random() * 10 1);var three Math.floor(Math.PI);JS methods: abs, ceil, cos, floor, log,max, min, pow, random, round, sin,sqrt, tanproperties: E, PICSC309

Special values: null and undefined28var ned null;var benson 9;var caroline;// at this point in the code,// ned is null// benson's 9// caroline is undefined JSundefined : has not been declared, does notexistnull : exists, but was specifically assigned anempty or null valueCSC309

Logical operators29 && ! ! ! most logical operators automatically convert types: 5 "7" is true 42 42.0 is true "5.0" 5 is true and ! are strict equality tests; checks bothtype and value "5.0"CSC309 5 is false

if/else statement (same as Java)30if (condition) {statements;} else if (condition) {statements;} else {statements;} JSidentical structure to Java's if/else statementJavaScript allows almost anything as a conditionCSC309

Boolean type31var iLike190M true;var ieIsGood "IE6" 0; // falseif ("web devevelopment is great") { /* true */ }if (0) { /* false */ }JS any value can be used as a Boolean "falsey"values: 0, 0.0, NaN, "", null, and undefined "truthy" values: anything else converting a value into a Boolean explicitly:var boolValue Boolean(otherValue); var boolValue !!(otherValue); CSC309

for loop (same as Java)32var sum 0;for (var i 0; i 100; i ) {sum sum i;}var s1 "hello";var s2 "";for (var i 0; i s.length; i ) {s2 s1.charAt(i) s1.charAt(i);}// s2 stores "hheelllloo"CSC309JSJS

while loops (same as Java)33while (condition) {statements;}do {statements;} while (condition); JSJSbreak and continue keywords also behave as in JavaCSC309

Popup boxes34alert("message"); // messageconfirm("message"); // returns true or falseprompt("message"); // returns user input stringJS

Arrays35var name []; // empty arrayvar name [value, value, ., value]; // pre-filledname[index] value; // store elementJSvar ducks ["Huey", "Dewey", "Louie"];var stooges []; // stooges.length is 0stooges[0] "Larry"; // stooges.length is 1stooges[1] "Moe"; // stooges.length is 2stooges[4] "Curly"; // stooges.length is 5stooges[4] "Shemp"; // stooges.length is 5CSC309JS

Array methods36var a ["Stef", "Jason"]; // Stef, Jasona.push("Brian"); // Stef, Jason, Briana.unshift("Kelly"); // Kelly, Stef, Jason, Briana.pop(); // Kelly, Stef, Jasona.shift(); // Stef, Jasona.sort(); // Jason, StefJS array serves as many data structures: list, queue, stack, .methods: concat, join, pop, push, reverse, shift,slice, sort, splice, toString, unshiftpush and pop add / remove from back unshift and shift add / remove from front shift and pop return the element that is removed

String type37varvarvarvar s "Connie Client";fName s.substring(0, s.indexOf(" ")); // "Connie"len s.length; // 13s2 'Melvin Merchant';JSmethods: charAt, charCodeAt, fromCharCode,indexOf, lastIndexOf, replace, split,substring, toLowerCase, toUpperCase charAt returns a one-letter String (there is no char type)length property (not a method as in Java)Strings can be specified with "" or ''concatenation with : 1 1 is 2, but "1" 1 is "11"

More about String38 escape sequences as in Java: \' \" \& \n \t \\converting between numbers and Strings:var count 10;var s1 "" count; // "10"var s2 count " bananas, ah ah ah!"; // "10 bananas, ahah ah!"var n1 parseInt("42 is the answer"); // 42var n2 parseFloat("booyah"); // NaNJS accessing the letters of a String:var firstLetter s[0]; // fails in IEvar firstLetter s.charAt(0); // does work in IEvar lastLetter s.charAt(s.length - 1);JSCSC309

Splitting strings: split and join39var s "the quick brownvar a s.split(" "); //a.reverse();//s a.join("!");// split breaks apart a string into an array using adelimiter can fox";["the", "quick", "brown", "fox"]["fox", "brown", "quick", "the"]"fox!brown!quick!the"JSalso be used with regular expressions (seen later)join merges an array into a single string, placing adelimiter between them

40JavaScript Object Hierarchy

The Browser Object Hierarchy41

The Browser Objects (Global DOM)42namedescriptiondocumentcurrent HTML page and its contenthistorylist of pages the user has visitedlocationURL of the current HTML pagenavigatorinfo about the web browser you are usingscreeninfo about the screen area occupied bythe browserwindowthe browser window

The window object43 the entire browser window (DOM top-level object)technically, all global code and variables becomepart of the window object properties: document, history, location, namemethods: alert, confirm, prompt (popup boxes)setInterval, setTimeout clearInterval,(timers)(popping up new browser windows)clearTimeout open, close blur, focus, moveBy, moveTo, print, resizeBy,resizeTo, scrollBy, scrollTo

The document object (details soon)44 the current web page and the elements inside itproperties: anchors, body, cookie, domain, forms,images, links, referrer, title, URLmethods:getElementById getElementsByName getElementsByTagName close, open, write, writeln CSC309

The location object45 the URL of the current web pageproperties: host, hostname, href, pathname, port,protocol, searchmethods: CSC309assign, reload, replace

The navigator object46 information about the web browser applicationproperties: appName, appVersion, browserLanguage,cookieEnabled, platform, userAgentSome web programmers examine the navigatorobject to see what browser is being used, and writebrowser-specific scripts and hacks:if (navigator.appName "Microsoft Internet Explorer"){ .JSCSC309

The screen object47 information about the client's display screenproperties: availHeight,availWidth, colorDepth,height, pixelDepth, widthCSC309

The history object48 the list of sites the browser has visited in this windowproperties: methods: lengthback, forward, gosometimes the browser won't let scripts viewhistory properties, for securityCSC309

49The DOM tree

The DOM tree50

Types of DOM nodes51 p This is a paragraph of text with a a href "/path/page.html" link in it /a . /p element nodes (HTML tag) can have children and/or attributestext nodes (text in a block element)attribute nodes (attribute/value pair) text/attributesare children in an element node cannot have children or attributes not usually shown when drawing the DOM treeHTML

Types of DOM nodes52 p This is a paragraph of text with a a href "/path/page.html" link in it /a . /p CSC309HTML

Traversing the DOM tree53name(s)descriptionfirstChild, lastChildstart/end of this node's list ofchildrenchildNodesarray of all this node's childrennextSibling, previousSiblingneighboring nodes with the sameparentparentNodethe element that contains thisnodecomplete list of DOM node propertiesbrowser incompatiblity information

DOM tree traversal example54 p id "foo" This is a paragraph of text with a a href "/path/to/another/page.html" link /a . /p HTML

Elements vs text nodes55 div p This is a paragraph of text with a a href "page.html" link /a . /p /div HTMLQ: How many children does the div above have?A: 3 anelement node representing the p two text nodes representing "\n\t" (before/after theparagraph) Q: How many children does the paragraph have?Q: The a tag?

Selecting groups of DOM objects56 methods in document and other DOM objects foraccessing urns array of descendentswith the given tag, such as "div"getElementsByNamereturns array of descendantswith the given name attribute(mostly useful for accessingform controls)CSC309

Getting all elem. of a certain type57var allParas document.getElementsByTagName("p");for (var i 0; i allParas.length; i ) {allParas[i].style.backgroundColor "yellow";}JS body p This is the first paragraph /p p This is the second paragraph /p p You get the idea. /p /body CSC309HTML

Combining with getElementById58var addrParas gName("p");for (var i 0; i addrParas.length; i ) {addrParas[i].style.backgroundColor "yellow";}JS p This won't be returned! /p div id "address" p 1234 Street /p p Atlanta, GA /p /div CSC309HTML

Creating new )creates and returns a new emptyDOM node representing an elementof that typedocument.createTextNode("text")creates and returns a text nodecontaining given text// create a new h2 nodevar newHeading document.createElement("h2");newHeading.innerHTML "This is a heading";newHeading.style.color "green";JS merely creating a node does not add it to the pageyou must add the new node as a child of an existingelement on the page.

Modifying the DOM tree60namedescriptionappendChild(node)places given node at end of thisnode's child listinsertBefore(new, old)places the given new node in thisnode's child list just before old childremoveChild(node)removes given node from this node'schild listreplaceChild(new, old)replaces given child with new nodevar p document.createElement("p");p.innerHTML "A Child(p);JS

Removing a node from the page61function slideClick() {var bullets document.getElementsByTagName("li");for (var i 0; i bullets.length; i ) {if (bullets[i].innerHTML.indexOf("children") 0){bullets[i].removeChild();}}}JS each DOM object has a removeChild method toremove its children from the page

DOM versus innerHTML hacking62Why not just code the previous example this way?function slideClick() {document.getElementById(“thisslide").innerHTML " p A paragraph! /p ";}JS Imagine that the new node is more complex:ugly: bad style (e.g. JS code embedded within HTML) error-prone: must carefully distinguish " and ' can only add at beginning or end, not in middle of child list function slideClick() {this.innerHTML " p style 'color: red; " "margin-left: 50px;' " "onclick 'myOnClick();' " "A paragraph! /p ";}JS

63Unobtrusive JavaScriptCSC309

Unobtrusive JavaScript64 JavaScript event code seen previously wasobtrusive, in the HTML; this is bad stylenow we'll see how to write unobtrusive JavaScriptcode HTMLwith minimal JavaScript inside uses the DOM to attach and execute all JavaScriptfunctionsCSC309

Unobtrusive JavaScript65 allows separation of web site functionality into: content(HTML) - what is it? presentation (CSS) - how does it look? behavior (JavaScript) - how does it respond to userinteraction?CSC309

Obtrusive event handlers (bad)66 button id "ok" onclick "okayClick();" OK /button HTML// called when OK button is clickedfunction okayClick() {alert("booyah");} JSthis is bad style (HTML is cluttered with JS code)goal: remove all JavaScript code from the HTMLbodyCSC309

67Attaching an event handler inJavaScript code// where element is a DOM element objectelement.event function;JSdocument.getElementById("ok").onclick okayClick; JSit is legal to attach event handlers to elements'DOM objects in your JavaScript code noticethat you do not put parentheses after thefunction's name this is better style than attaching them in the HTMLWhere should we put the above code?CSC309

When does my code run?68 head script src "myfile.js" type "text/javascript" /script /head body . /body HTML// global codevar x 3;function f(n) { return n 1; }function g(n) { return n - 1; }x f(x); JSyour file's JS code runs the moment the browserloads the script tag anyvariables are declared immediately any functions are declared but not called, unless yourglobal code explicitly calls them

When does my code run?69 head script src "myfile.js" type "text/javascript" /script /head body . /body HTML// global codevar x 3;function f(n) { return n 1; }function g(n) { return n - 1; }x f(x); JSat this point in time, the browser has not yet readyour page's body noneof the DOM objects for tags on the page havebeen createdCSC309

A failed attempt to be unobtrusive70 head script src "myfile.js" type "text/javascript" /script /head body div button id "ok" OK /button /div HTML// global codedocument.getElementById("ok").onclick okayClick;// error: ("ok") is null JSproblem: global JS code runs the moment the scriptis loadedscript in head is processed before page's body hasloaded noelements are available yet or can be accessed yetvia the DOM

The window.onload event71// this will run once the page has finished loadingfunction functionName() {element.event functionName;element.event functionName;.}window.onload functionName; // global codeJS we want to attach our event handlers right after thepage is done loading thereis a global event called window.onload eventthat occurs at that moment (after the page is loaded) in window.onload handler we attach all theother handlers to run when events occur

An unobtrusive event handler72 !-- look Ma, no JavaScript! -- button id "ok" OK /button HTML// called when page loads; sets up event handlersfunction pageLoad() {document.getElementById("ok").onclick okayClick;}function okayClick() {alert("booyah");}window.onload pageLoad; // global codeJSCSC309

Anonymous functions73function(parameters) {statements;} JSJavaScript allows you to declare anonymousfunctionsquickly creates a function without giving it a namecan be stored as a variable, attached as an eventhandler, etc.CSC309

Anonymous function example74window.onload function() {var okButton document.getElementById("ok");okButton.onclick okayClick;};function okayClick() {alert("booyah");}JSCSC309

The keyword this75this.fieldName // access fieldthis.fieldName value; // modify fieldthis.methodName(parameters); // call method JSall JavaScript code actually runs inside of an objectby default, code runs inside the global windowobject allglobal variables and functions you declare becomepart of window the ‘this’ keyword refers to the current objectCSC309

The keyword this76function pageLoad() {document.getElementById("ok").onclick okayClick;// bound to okButton here}function okayClick() { // okayClick knows what DOM objectthis.innerHTML "booyah"; // it was called on}window.onload pageLoad;JS event handlers attached unobtrusively are bound tothe elementinside the handler, that element becomes this (ratherthan the window)CSC309

Canvas canvas element is used to draw graphics, on the fly,via scripting (usually JavaScript). only a container for graphics. You must use a script toactually draw the graphics.

Canvas Resources to www.w3schools.com/tags/ref /Web/API/Canvas API/Tutorial/Basic animations

Event-driven programming 13 ! you are used to programs that start with a main method (or implicit main like in PHP) ! JavaScript programs instead wait for user actions called events and respond to them ! event-driven programming: writing programs driven by user even