420 likes | 705 Vues
Javascript Event Driven programming, Intro to DOM , Arrays, Styling, etc. chapters 8 & 9&11 JavaScript Tutorial at http://www.w3schools.com/js/. Event-driven programming. JS programs have no main; they respond to user actions called events
E N D
JavascriptEvent Driven programming, Intro to DOM, Arrays, Styling, etc. chapters 8 & 9&11 JavaScript Tutorial at http://www.w3schools.com/js/
Event-driven programming • JS programs have no main; they respond to user actions called events • event-driven programming: writing programs driven by user events
HTML Buttons: <button> the canonical clickable UI control (inline) <button>Click me!</button> • button's text appears inside tag; can also contain images • To make a responsive button or other UI control: • choose the control (e.g. button) and event (e.g. mouse click) of interest • write a JavaScript function to run when the event occurs • attachthe function to the event on the control • statements placed into functions can be evaluated in response to user events
Event handlers: onclickevent and attribute <elementattributesonclick="function();">... <button onclick="myFunction();">Click me!</button> • JavaScript functions can be set as event handlers • when you interact with the element, the function will execute • onclick is just one of many event HTML attributes we'll use function myFunction() { alert("Hello!"); alert("How are you?"); } … <head> <script src=“button.js" type="text/javascript"> </script> </head> <body> <button onclick="myFunction();">Click me! </button> <body> … • but popping up an alert window is disruptive and annoying • A better user experience would be to have the message appear on the page...
Document Object Model (DOM) • most JS code manipulates elements on an HTML page • we can examine elements' state • e.g. see whether a box is checked • we can changestate • e.g. insert some new text into a div • we can changestyles • e.g. make a paragraph red a set of JavaScript objects that represent each element on the page
DOM-getElementById • The getElementById method, given an id as an argument, finds the HTML element with a matching id attribute and returns a JavaScript object representing the element.
Accessing elements: document.getElementByIdvalueversus innerHTML • document.getElementByIdreturns the DOM object for an element with a given id. • value property of a JavaScript object representing an HTML text input element specifies the text to display in the text field. • You can change the text in most formcontrols by setting the valueproperty • innerHTML property can be used in a script to set the contents of HTML container (e.g. div, span, p) element’s. • change the text inside most container elements by setting the innerHTMLproperty
Accessing elements: document.getElementByIdvalueproperty example varname = document.getElementById("id"); <script src="replace.js" type="text/javascript"></script> </head> <body> <button onclick="changeText();">Click me!</button> <input id="output" type="text" value="replace me" /> </body> function changeText() { var textbox = document.getElementById("output"); textbox.value = "Hello, world!"; }
Accessing elements: document.getElementByIdinnerHTMLexample <script src="replace2.js" type="text/javascript"></script </head> <body> <button onclick="swapText();">Click me!</button> <span id="output2">Hello</span> <input id="textbox2" type="text" value="Goodbye" /> </body> Replace2.htm function swapText() { var span = document.getElementById("output2"); vartextBox = document.getElementById("textbox2"); var temp = span.innerHTML; span.innerHTML= textBox.value; textBox.value = temp; } replace2.js
<head> <title>CMPS 278 Tip Calculator</title> <link href="tip_files/tip.css" type="text/css" rel="stylesheet"> <script src="tip_files/tip.js" type="text/javascript"></script> </head> <body> <h1>CMPS 278 Tip Calculator</h1> <div> <input id="subtotal" type="text"> $ Subtotal <br> <input id="tip" type="text"> % Tip <hr> </div> <div id="output"> <h2>Your total:</h2> <pid="total">$0.00</p> </div> <div> <button onclick="cool();">Calculate Tip</button> </div> </body> Another example tip.html function cool() { var subtotal = document.getElementById("subtotal").value; var tip = document.getElementById("tip").value; var total = parseInt(subtotal) + parseInt(subtotal)*(parseFloat(tip)/100.0); document.getElementById("total").innerHTML = total; } tip.js
Arrays var n2 = new Array(); // allocate empty Array var n1 = new Array( 5 ); // allocate five-element Array var name = []; // empty array var colors = new Array(value, value, ..., value); var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element. • JavaScript arrays are Arrayobjects . • Creating arrays using the newoperator is known as creating an object instance • JavaScript reallocates an Arraywhen a value is assigned to an element that is outside the bounds of the original Array • Elements between the last element of the original Arrayand the new element have undefined values • Referring to an element outside the Arraybounds is a logic error. • Arrays can be created using a comma-separated initializer list enclosed in square brackets ([]) • The array’s size is determined by the number of values in the initializer list • The initial values of an array can be specified as arguments in the parentheses following newArray • The size of the array is determined by the number of values in parentheses
Arrays //Creates an array with all elements are defined var colors = new Array( "cyan", "magenta","yellow", "black" ); var ducks = ["Huey", "Dewey", "Louie"]; // Creates an array with four elements, two of which reserve space for values to //be specified later var integers2 = [ 2, , , 8 ]; // Creates an empty array then add elements to it var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[4] = "Curly"; // stooges.length is 5 stooges[4] = "Shemp"; // stooges.length is 5// store element. • several ways to initialize an array • length property (grows as needed when elements are added) • JavaScript arrays are “dynamic” entities that can change size after they are created
Arrays • Two ways to pass arguments to functions (or methods) • Pass-by-value • Numbers, boolean values and strings are passed to functions by value. • Pass-by-reference • All objects are passed to functions by reference • Arrays are objects in JavaScript, so Arrays are passed to a function by reference • To pass an array as an argument to a function, just specify the name of the array (a reference to the array) without brackets • Although entire arrays are passed by reference, individual elementsare passed by value • To pass an array element to a function, use the subscriptedname of the element as an argument in the function call
Arrays initarray.js // Initializer list specifies the number of elements and a value for each element. var colors = new Array( "cyan", "magenta","yellow", "black" ); var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ]; outputArray( "Array colors contains", colors ); outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); // output the heading followed by a two-column table containing the subscripts and elements of theArray function outputArray( heading, theArray ) { document.writeln( "<h2>" + heading + "</h2>" ); document.writeln( "<table border = \"1\"" ); document.writeln( "<thead><th>Subscript</th>" + "<th>Value</th></thead><tbody>" ); // output the subscript and value of each array element for ( vari = 0; i < theArray.length; i++ ) document.writeln("<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>"); document.writeln( "</tbody></table>" ); }// end function outputArray <head> <title>Initializing an Array with a Declaration</title> <style type = "text/css"> table { width: 15em } th { text-align: left } </style > <script src="initarray.js" type="text/javascript"></script> </head> <body></body>
Arrays (sorting an Array) • The sort() method sort the items of an array. • takes one optional argument, defining the sort order which can be either alphabetic or numeric, and either ascending or descending. • Default sort order is alphabetic and ascending • when numbers are sorted alphabetically, "40" comes before "5“ • To perform a numeric sort, you must pass an argument when calling the sort method. • The argument must be a function that takes two arguments, compares the two arguments, and returns one of the following three values: -1, 0, 1 if the first argument is less than, equal to, or greater than the second, respectively • Functions in JavaScript are considered to be data and can be assigned to variables, stored in Arrays and passed to functions just like other data
Arrays sort.js var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( "<h1>Sorting an Array</h1>" ); outputArray( "Array 'a' data items in original order: ", a ); outputArray( "Array 'fruits' data items in original order: ", fruits ); fruits.sort(); outputArray( "Array 'fruits' data items in ascending order: ", fruits); a.sort(); outputArray( "Array 'a' data items in default order: ", a); a.sort( compareIntegers ); // sort the array outputArray("Array 'a' data items in ascending order: ", a); // output the heading followed by the contents of theArray function outputArray( heading, theArray ){ document.writeln( "<p>" + heading + theArray.join( " " ) + "</p>" ); } // end function outputArray // comparison function for use with sort functioncompareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); } // end function compareIntegers <head> <title>Sorting an Array with Array Method sort</title> <script src= "sort.js" type="text/javascript"></script> </head> <body></body>
More Array methods var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Banana,Orange,Apple, fruits.push("Kiwi"); // Banana,Orange,Apple,Kiwi fruits.shift() //Orange,Apple,Kiwi fruits.unshift("Lemon","Pineapple"); // Lemon,Pineapple,Orange,Apple,Kiwi
More Array methods var fruits = ["Banana", "Orange", "Apple", "Mango"]; //slice the elements starting at index 1, and ends at, but does not include, index 3 varar = fruits.slice(1,3) // Orange, Apple (in ar) // At position 1, add the new items: ar.splice(1,0,"Lemon","Kiwi"); // Orange,Lemon,Kiwi,Apple //At position 2, remove 1 item and add the new items, : ar.splice(2,1,“Banana",“Mango"); // Orange, Lemon,Banana,Mango,Apple // At position 2, remove 2 items: ar.splice(2,2);//Orange,Lemon,Apple fruits.toString(); // Banana,Orange,Apple,Mango fruits.reverse(); // Mango,Apple,Orange,Banana (in fruits) fruits.splice(1, 1); // Mango,Orange,Banana (in fruits) var basket = fruits.concat(ar); // Mango,Orange,Banana,Orange,Lemon,Apple(in basket)
for …in and join method • Thejoin() method joins the elements of an array, separated by the separator supplied in the function’s argument, into a stringand returns the string • If an argument is not specified, the comma is used as default separator • for…in statement • Enables a script toperform a task for each element in an array • skips any undefined elements in the array. var fruits = ["Banana", "Orange", "Apple", "Mango"]; var energy = fruits.join(); //The result of energy will be: Banana,Orange,Apple,Mango var energy = fruits.join(" and "); //The result of energy will be: Banana and Orange and Apple and Mango for ( var j in fruits ){ document.write(fruits [j] + " "); // Banana Orange Apple Mango }
Linearsearch.htm <html > <head> <title>Linear Search of an Array</title> <script src= "linearsearch.js" type="text/javascript"></script> </head> <body> <form action = ""> <p>Enter integer search key<br /> <input id = "inputVal" type = "text" /> <input type = "button" value = "Search" onclick = "buttonPressed()"/> <br /> </p> <p>Result<br /> <input id = "result" type = "text" size = "30" /> </p> </form> </body> </html>
var a = new Array( 100 ); // create an Array // fill Array with even integer values from 0 to 198 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; // function called when "Search" button is pressed function buttonPressed(){ // get the input text field var inputVal = document.getElementById( "inputVal" ); // get the result text field var result = document.getElementById( "result" ); // get the search key from the input text field var searchKey = inputVal.value; //Array a is passed to linearSearch even though it is a // global variable. Normally an array will be passed to //a method for searching. var element = linearSearch( a, parseInt( searchKey ) ); if ( element != -1 ) result.value = "Found value in element " + element; else result.value = "Value not found"; } // end function buttonPressed // Search "theArray" for the specified "key" value function linearSearch( theArray, key ) { // iterates through each element of the array in order for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; return -1; } // end function linearSearch Linear search.js
Splitting strings: split and join var s = "the quick brown fox"; var a = s.split(" "); // ["the", "quick", "brown", "fox"] a.reverse(); // ["fox", "brown", "quick", "the"] s = a.join("!"); // "fox!brown!quick!the" • splitbreaks apart a string into an array using a delimiter • can also be used with regular expressions (seen later) • joinmerges an array into a single string, placing a delimiter between them
Scope • Global variables or script-level are accessible in any part of a script and are said to have global scope • Thus every function in the script can potentially use the variables • Local variables of a function and function parameters have function scope • If a local variable in a function has the same name as a global variable, the global variable is “hidden” from the body of the function. 24 24
The arguments array function example() { for (vari = 0; i < arguments.length; i++) { alert(arguments[i]); } } example("how", "are", "you"); // alerts 3 times • every function contains an array named argumentsrepresenting the parameters passed • can loop over them, print/alert them, etc. • allows you to write functions that acceptvarying numbers of parameters 25
Arrays as maps var map = []; map[42] = "the answer"; map[3.14] = "pi"; map["champ"] = "suns"; • the indexes of a JS array need not be integers! • this allows you to store mappings between an index of any type ("keys") and value • similar to Java's Map collection or a hash table data structure 26
two-dimensional Arrays • In general, an array with m rows and n columns is called an m-by-narray • Two-dimensional array element accessed using an element name of the form a[ i ][ j ] • a is the name of the array • i and j are the subscripts that uniquely identify the row and column • Multidimensional arrays are maintained as arrays of arrays • can be initialized in declarations like a one-dimensional array, with values grouped by row in square brackets • The rows of a two-dimensional array can vary in length 27
two-dimensional Arrays as maps vararray1 = [ [ 1, 2, 3 ], // first row [ 4, 5, 6 ] ]; // second row vararray2 = [ [ 1, 2 ], // first row [ 3 ], // second row [ 4, 5, 6 ] ]; // third row outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); functionoutputArray( heading, theArray) { document.writeln( "<h2>" + heading + "</h2><pre>" ); // iterates through the set of one-dimensional arrays for ( variin theArray ) { // iterates through the elements of each one-dimensional array for ( varj in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); document.writeln( "<br />" ); } // end for document.writeln( "</pre>" ); } // end function outputArray 28
OnloadEvent • If a script in the headattempts to get a DOM node for an HTML element in the body, getElementByIdreturns nullbecause the body has not yet loaded • onloadproperty of the body element calls an event handler when the <body>of the HTML document is completely loaded into the browser window <body onload = "functionName ()"> 29 29
onload event <html> <head> <script type="text/javascript"> function myFunction() { varaddr = document.getElementById("address"); addr.innerHTML = "this is what will be shown"; } </script> </head> <body> <p>This won't be changed!</p> <div id="address"> <p>1234 Street</p> <p>Atlanta, GA</p> </div> </body> </html> <body onload = "myFunction()">
The eval(evil?) function eval("JavaScript code"); eval("var x = 7; x++; alert(x / 2);"); // alerts 4 • evaltreats a String as JavaScript code and runs that code • This is occasionally useful, but usually a very bad idea • if the string's contents come from user input, the user can cause arbitrary code execution • can lead to security problems and bugs 31
The typeof function typeof(value) • given these declarations: • function foo() { alert("Hello"); } • var a = ["Huey", "Dewey", "Louie"]; • The following statements are true: • typeof(3.14) === "number" • typeof("hello") === "string" • typeof(true) === "boolean" • typeof(foo) === "function" • typeof(a) === "object" • typeof(null) === "object" • typeof(undefined) === "undefined" 32
JavaScript in HTML body (example) <script type="text/javascript"> JavaScript code </script> • JS code can be embedded within your HTML page's head or body • runs as the page is loading • this is considered bad styleand should be avoided. • mixes HTML content and JS scripts (bad) • can cause your page not to validate 33
Some of the DOM object properties <div id="main" class="foo bar"> <p>Hello, <em>very</em> happy to see you!</p> <imgid="icon" src="images/borat.jpg" alt="Borat" /> </div>
DOM properties for form controls <input id="sid" type="text" size="7" maxlength="7" /> <input id="frosh" type="checkbox" checked="checked" /> Freshman?
Abuse of innerHTML // bad style! var paragraph = document.getElementById("welcome"); paragraph.innerHTML = "<p>text and <a href="page.html">link</a>"; • innerHTML can inject arbitrary HTML content into the page • however, this is prone to bugs and errors and is considered poor style • Most programmers avoid using innerHTML to inject HTML tags; and use it to inject plain text only • document.write/writeln() also injects HTML code into the HTML page • But later on we will use the DOM methods to create HTML elements and add them to our web page.
Adjusting styles with the DOM <button id="clickme">Color Me</button> HTML window.onload = function() { document.getElementById("clickme").onclick = changeColor; }; function changeColor() { varclickMe = document.getElementById("clickme"); clickMe.style.color = "red"; } • contains same properties as in CSS, but with camelCasedNames • examples: backgroundColor, borderLeftWidth, fontFamily • window.onloadevent occurs when the browser has finished loading the page (will be discussed later) JS
Common DOM styling errors • many students forget to write .style when setting styles • style properties are capitalizedlikeThis, not like-this • style properties must be set as strings, often with units at the end • write exactly the value you would have written in the CSS, but in quotes