729G26 – Interaction programming Lecture2 Semi-supervised lab sessions ⁃ TAoncall ⁃ PageTAviaCamedin http://www.camedin.com/live/f7b945b8199d412a914 28f561d2d0003 ⁃ linkalsoon homepage Lecture overview ⁃ Publishing contentontheweb ⁃ WhatisJavaScript ⁃ Overviewof theJavaScriptlanguage ⁃ JavaScriptandHTML,sittinginaDOMtree ⁃ Creatinginteractionusing JavaScript- listeningtoevents andreactingtothem Todays lecture in the context of the course ⁃ JavaScriptisthefoundation ofallinteractionprogramming fortheweb. ⁃ Usetodayslecturetofindentrypoints intothemagical worldofJavaScript Todays lecture in the context of the course ⁃ Lectures3,4and5 jQuery- aJavaScriptframeworkformoreefficientweb development Using3rdpartylibraries Git(Hub) Precedentdesignanalysis Publishing content on the web How does the web work? web server web browser DNS Google Server Farm Hamina, Finland LiU EXPANDING REALITY Web servers ⁃ Examples ApacheHTTPServer ApacheTomcat MicrosoftInternetInformationServices(IIS) nginx lighttpd Jigsaw Web server market share Source: Netcraft November 2013 survey The Browser DNS - Domain Name Server 0701-111111 Contacts 0701-222222 http://www.flickr.com/photos/jamescridland/277673803/ http://www.flickr.com/photos/dimi3/537121203/ Andy Contacts Andy : 0701-111111 Chris: 0701-222222 Chris Chris http://www.flickr.com/photos/jamescridland/277673803/ http://www.flickr.com/photos/dimi3/537121203/ DNS 111.222.111.222 123.213.34.10 http://www.flickr.com/photos/mayhem/2939259129/ http://www.flickr.com/photos/pleeker/105637465/ DNS twitter.com: 111.222.111.222 google.com: 123.213.34.10 twitter.com google.com http://www.flickr.com/photos/mayhem/2939259129/ http://www.flickr.com/photos/pleeker/105637465/ Publishing web content at IDA ~/www-pub/index.html Web Page Web Page Web Page WWW Web Page DNS WWW Server DNS Server Web Page Internet http://www-und.ida.liu.se/~liuid/index.html From a PC @ IDA ⁃ Thewww-pub directoryinyourhomedirectory isvisible ontheweb(createitifitdoesnotexist) ⁃ Allfilesanddirectoriesreadablebyotherusersarevisible ontheweb. ⁃ E.g.topublish afilenamedindex.html, putitin Z:\www-pub ⁃ Theurl tothefile: http://www-und.ida.liu.se/~studentID/index.html Set permissions for files and folders ⁃ Makesurethatthegroup “Everyone”isallowedtoread thefilesanddirectoriesyouwanttopublish ontheweb. ⁃ Moreinformation https://www.ida.liu.se/local/students/homepage.en.shtml From any other computer ⁃ Logintoremote-und.ida.liu.se viaSFTP.Useyour LiU-IDandpassword. ⁃ Uploadfiles/folders towww-pub ⁃ Makesurefiles/folders arereadabletothe“other” group. ⁃ Minitutorialat http://www.ida.liu.se/~jodfo01/kompis/#!sftpfiletransfer.md Demo JavaScript Codelas for today https://www.ida.liu.se/codela/as/729g26b What is JavaScript ⁃ JavaScriptisaprogramming language thatisusedinmany different applications. ⁃ JavaScriptisnot Java,theyarecompletelyseparate beings. ⁃ Formallyspecified asECMAScript http://www.ecma-international.org/publications/standards/Ecma-262.htm ⁃ Programming languagefeatures interpreted- likePython dynamicallytyped- likePython prototype-based programming(similaritieswithOOP) Where is JavaScript used ⁃ Inwebbrowsers- clientsidescripting ⁃ Onservers- server-sidescripting (e.g.Node.js) ⁃ Google ChromeExtensionsarewritteninJavaScript ⁃ AcrobatReadersupports JavaScriptinPDFfiles ⁃ Photoshop, Illustrator,Dreamweaver&InDesignsupport scripting usingJavaScript ⁃ ActionScript, used inAdobe FlashisECMAScript kingdatoro redspotted airdiogo waltstonebu rner goron waltstoneburner redspotted garrettc millerdial JavaScript is JavaScript, is JavaScript? ⁃ Thelanguage andsyntaxisthesame ⁃ TheAPIweuseJavaScripttotalktoisdifferent. Google Chrome Extension JavaScript for PDFs - annotation Creating a HTTP server in Node.js Get div nodes from HTML DOM Web browser, client side scripting ⁃ Changing HTMLcontent ⁃ Handling userinteraction ⁃ Communicating withserversidesoftware ⁃ Responsivedesign ⁃ Triggering certainkindsofanimation ⁃ Basically- everything thatmakesthewebcomealive. JavaScript resources http://javascript.crockford.com/javascript.html https://developer.mozilla.org/en-US/docs/Web/JavaScript http://docs.webplatform.org/wiki/javascript http://www.w3schools.com/js/ The console Whereyoucanexamineerrormessages Syntax ⁃ Beforewecandoallthecoolstuff, weneedtolearnhow tospeakJavaScript- syntaxandvocabulary ⁃ statementsandcomments ⁃ variables ⁃ datatypes ⁃ functions ⁃ conditional statements ⁃ loops Codecademy exercises ⁃ Codecademyexercisestopracticeyour JavaScript. ⁃ Codecademyexercisesshould becompleted byeach group member. ⁃ YouwillnotlearnJavaScriptduring thislecture,youwill getanoverviewadaptedtoyourprerequisite knowledge ofprogramming. Comments and statements Variables // a variable is declared using the var keyword var myVariable; // a variable is set using the = character myVariable = 5; // a variable can be declared and set at the same time var myOtherVar = 6; // more than one variable can be declared and set at the same time var x, y, z;var p = 0, q = "hello", s = true; Levels of nothing ⁃ Whenavariableisdeclared,but notset undefined ⁃ Whenavariableisdeclaredandwewantittohavean empty value null ⁃ Tryingtoaccessavariablethathasnotbeendeclaredwill resultinaReferenceError Datatypes ⁃ Numbers ⁃ Booleans ⁃ Strings ⁃ Arrays ⁃ Objects Numbers and operators // all numbers in JavaScript are stored as floating point numbers var a = 3; var b = 2.0; // we can use the operators we expect from e.g. python console.log(a+b); console.log(a-b); console.log(a/b); console.log(a*n); JavaScript has two boolean values ⁃ false ⁃ true ⁃ Thefollowing evaluatetofalse,everything elseevaluates totrue 0 null "" false Strings Assignment operators Arrays // An array in JavaScript is similar to the list in python // we can create a new, empty array in different ways var myArray1 = new Array(); var myArray2 = Array(); var myArray3 = []; // we can fill an array when initializing it var myArray4 = [1, 2, "hello"]; // we can set any position in an array, empty spots will be undefined myArray4[10] = "what!"; // myArray4: [1, 2, "hello", undefined ? 7, "what"] Objects ⁃ JavaScriptisanobjectoriented language. ⁃ However:basedonprototypes, ratherthanclasses. ⁃ Objectshaveproperties. ⁃ Properties areaccessedusing dotnotation: object.property ⁃ Objectscanalsohavefunctions thatcanbehaveas methods. ⁃ Functions inobjectsarecalledusingdot notation: object.function() Functions ⁃ namedfunctions ⁃ anonymous functions ⁃ function objects Function examples // a named function function helloWorld() { console.log("hello world"); } // defining an anonymous function, and keeping a reference to // its function object anonymous = function() { console.log("Anonymous hello world"); } // grabbing the function object of a named function hello = helloWorld; Variable scope Conditional statements Comparison operators ⁃ equalvalue(withtypeconversion): == ⁃ equalvalueanddatatype (notypeconversion): === ⁃ lessthan:< ⁃ lessthanorequal:<= ⁃ greaterthan:> ⁃ greaterthanorequal:>= ⁃ different value:!= ⁃ different valueordifferenttype:!== Logical operators ⁃ not:! ⁃ and:&& ⁃ or:|| Loops ⁃ while ⁃ dowhile ⁃ for ⁃ breakandcontinue The while loop - while this is true, do this The do while loop - do this, if this is true, loop for loop - special while loop As in e.g. python, we can break and continue ⁃ break:abortcurrentloop ⁃ continue:skiptherestof thecurrentiterationandmove tothenextiteration Keeping code clean is up to the programmer in JavaScript. Be consistent, or be in trouble A note on JavaScript code style ⁃ usecamelCaseforvariableandfunction names ⁃ startvariableandfunction nameswithalowercaseletter ⁃ usemeaningful namesforvariableandfunction names Connecting the script to the content ⁃ Twowaysof addingJavaScripttoanHTMLfile ⁃ Usethe<script> tagandinlineJavaScript ⁃ Usethe<script> tagwiththesrcattribute Where to load the JavaScript ⁃ Thescriptisrun whenloaded. ⁃ Ifthescriptdepends on e.g.existingelementsonthe page,weneedtoloadthescriptwhenthoseelements havebeenloaded. ⁃ E.g. lastinthe<body> tag. usingthewindow.onload eventhandler(we’llgettothislater) JavaScript and the DOM ⁃ ⁃ ⁃ ⁃ MoreabouttheDOM WhatcanwedowiththeDOMusingJavaScript Howcanweusethistocreateinteraction? Whattypesofinteraction- input/output- canweuseina webbrowser show/hide create/destroy move,position changeshape,color click, drag,drop- elements onpageandfiles fromthecomputer typeonkeyboard images,movies,animations The DOM tree ⁃ Importantnode types: element attribute text Why is the DOM tree so important? ⁃ TheDOMisthekeyintotheHTMLdocument. ⁃ Todoanything withtheHTMLdocument, youneedtouse theDOM ⁃ …so,without knowledge oftheDOM,youcannotdo interactionprogramming fortheweb. The DOM tree document ⁃ Thedocument’s children are elementnodes ⁃ Theelement’schildren are element element otherelements attributenodes element attribute atextnode attribute text text text attribute Accessing the DOM tree ⁃ Elements getanelementusingitsid getanarrayofelementsusingtheirclass accessinganelement’srelatives ⁃ Text getanelement’stextcontent usinginnerHTML ⁃ Attributes getanelement’sattributenodes getanelement’sspecificattributevalue Accessing elements Accessing element content Accessing attributes Editing the DOM tree ⁃ replaceinnerHTML ⁃ setattributes Change innerHTML and set an attribute value Creating new nodes in the DOM tree ⁃ Create ⁃ Initialize ⁃ Append orinsert Create an element node Create text nodes Add text nodes to elements Appending and inserting elements Changing an element’s CSS ⁃ Localstyle ⁃ Class Set an element’s style using JavaScript Manipulating style with class User interaction - event handling Elements have event handlers ⁃ Whenaneventistriggered inthecontextofanelement, itseventhandlersaretriggered ⁃ Eventexamples whenamouseenterstheareaofanelement whenamouseleavestheareaofanelement whenthemouseisclickedonanelement whenaformfieldisgivenfocus Event handling ⁃ Typicalmouseinteraction onmouseover onmouseout onclick ⁃ Typicalforminteraction onfocus onblur onsubmit Event handlers are references to functions ⁃ Wecansetanelementseventhandlertoanamed function objectorcreateananonymous function object Functions revisited ⁃ namedfunctions - adefined function withaname ⁃ anonymous functions - adefined function withoutaname ⁃ function objects- theactualfunction, whennamed, the nameisour“handle”onthefunction Function examples Writing an event handler