Published on

Published in: Technology, Design
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. 1 Client-side Scripting with JavaScript INFO 344 Winter 2007 Previously Creating documents with HTML Styling content with CSS Dynamic documents with PHP User input with web forms Usability, design Accessibility Any questions? The Project You should have an idea by today By Tuesday, Jan 30 you should have Description Diagram Wireframes Writing assignment is due Tuesday Feb 6 Examples/Ideas Metafilter http://www.metafilter.com/ http://www.jjg.net/ia/visvocab/files/m etafilter_ia.pdf This week Expanding our web toolkit JavaScript: Adding smartness to the browser Previously
  2. 2. 2 Adding client-side scripting JavaScript JavaScript is a client-side scripting language Executed by browser Can’t interact with the server (without help) Can’t directly interact with PHP Can’t interact with file system What JavaScript can do Perform simple computation Math, string operations, etc. Change page contents Add and remove HTML elements Change text and image contents Control the browser Navigate to pages Open windows Including JavaScript Can be included in page Use <script> tags within <head> Can be placed in an external file Create .js file with JS code in it Use <script> tag within <head> to link Embedding JS in a page <html> <head> <title>JavaScript Test</title> <script type="text/javascript"> var msg = "Hi everybody!"; alert(msg); </script> </head> <body> <!-- body goes here --> </body> </html> Linking to a JS file <html> <head> <title>JavaScript Test</title> <script type="text/javascript" src="library.js"/></script> </head> <body> <!-- body goes here --> </body> </html> in library.js: var msg = "Hi everybody!"; alert(msg);
  3. 3. 3 JavaScript language basics Statements Statements are terminated in a semicolon var hello = "Hi everybody"; var sum = 3 + 5; Variables Variable names don’t start with $ Declare variables similar to PHP sum = 4 + 5; name = “Jim"; Using var before a variable name gives it a global scope var age = 25; Types Number Both integers and floats String Single or double quotes OK Escape characters: n, t, " Boolean More on types Type casting uses a function syntax document.write("5" + 5); // 55 document.write(Number("5") + 5); // 10 Strings are concatenated using +, not . document.write(a + " plus " + b + " = " + (a+b)); Displaying output The document.write() function inserts its argument into the page document.write ("Hello, " + name + "!"); The alert() function presents its argument in a pop-up window alert("Hello, " + name + "!");
  4. 4. 4 Arrays Similar to PHP, some syntax differences var list = new Array(); // create new array list[0] = "bananas"; // add to index 0 alert(list[0]); // 0th item: "bananas" list.push("apples"); // use push to append size = list.length; // size of array: 2 list.sort(); // this one is a method list[2] = 5; // arrays can be of mixed type // now ["apples", "bananas", 5] More about arrays Associative arrays var zodiac = new Array(); zodiac["shaun"] = "Leo"; alert(zodiac["shaun"]); // "Leo" Shorthand declaration var groceries = new Array("bread", "milk", "cheese"); Loop through an array for (item in groceries) { document.write(item + "<br/>"); // writes all items } Loops Identical to PHP for (var i = 0; i < 20; i++) { document.write(I + "<br/>n"); } while (info344=="awesome") { comeToClass(); } Conditionals Uses else if, not elseif if (total > 21) { alert("you bust!); } else if (total < 22 && total >= 16) { alert("Stand!"); } else { alert("Hit!"); } Functions Nearly identical to PHP function power(base, exponent) { var total = 1; for (var i = 0; i < exponent; i++) { total = total * base; } return total; } Objects Can declare objects in JavaScript Use function syntax function Student(name, id) { this.name = name; this.id = id; } Use dot-notation to access them var betty = new Student("Betty", 100); alert (betty.id); // 100
  5. 5. 5 The eval function Can be used to execute arbitrary JS code held in a string Evaluates code and returns the result var sum = eval("2 + 7"); document.write(sum); // 9 Beware security issues Equivalent eval() function in PHP Escaping text Identical to PHP “” (backslash) alert(“To continue, please press the ”OK” button.”); ’ ” n = new line f = line feed r = carriage return & = ampersand Comments Identical to Java and PHP // this is a one-line comment /* this is a multi-line comment */ Using JavaScript Adding JavaScript to pages JavaScript may be used inline Output text in document, like PHP Most JavaScript is event-driven Define functions Attach functions to events (e.g. clicking a button) Functions run when the event occurs Inline JavaScript … <body> <p>Document last modified: <script type="text/javascript"> document.write(document.lastM odified); </script> </p> </body>
  6. 6. 6 Event-driven JavaScript <html><head> <script type="text/javascript"> function welcome() { alert("hey there!"); } </script> </head> <body> <form> <input type="button" value="Click me" onclick="welcome();"/> </form> </body></html> Input type "button" Button element Looks like submit button By default, does nothing Attribute "value" determines button text Use onclick to add behavior <input type="button" value="Click me" onclick="welcome();"/> onclick handler The onclick handler fires whenever an item is clicked Applies to most items that can be clicked on (links, buttons, images) May reference a function defined in a <script> tag <a href="#" onclick="alert('Hey!');"> This is a JavaScript-powered link</a> Other event handlers onclick onmouseover, onmouseout onblur, onfocus onload (for window object) onsubmit (for forms) … and many more! See http://www.quirksmode.org/js/events_compi nfo.html Referencing form elements Referencing elements Often we would like our scripts to reference an element on the page Get the contents of a text field Change color of some text Two methods for referencing page elements Form referencing Document Object Model (DOM)
  7. 7. 7 Referencing forms in JS When creating forms and inputs, we give each element a name Refer to object using document.formName.elementName <body> <form name="emailForm"> <input type="text" name="address"/> </form> </body> document.emailForm.address Accessing form values Attribute value contains the value of most form elements document.emailForm.address.value = "a@b.com"; // set alert(document.emailForm.address.value); // "a@b.com" Use checked attribute for checkboxes if (document.emailForm.cb1.checked) { // cb1 is checked … } else { // it's not … } The Document Object Model DOM provides a set of methods for accessing HTML elements (not just in forms) Takes advantage of XHTML's tree structure document object represents root page element Allows us to reference elements by ID or tag name And their parents, children and siblings Can be used to modify page attributes DOM methods document.getElementById(id) Retrieves the element with the specified id Returns an element object (more on this later) // gets the page element with id="email" email = document.getElementById("email"); // display contents of element with id="email" alert(email.value); More methods we'll talk about later The id attribute Can be added to any XHTML element Not just form elements id must be unique on page Form elements may have both name and id <body> <form name="emailForm"> <input type="text" name="address" id="address"/> </form> </body> document.emailForm.address, or document.getElementById("address") Changing page content with the DOM We can also change the content of an HTML element using its innerHTML property <script type="text/javascript"> // when this function fires, add text to paragraph function addResult() { document.getElementById("change").innerHTML ="HI"; //c.innerHTML = "Success!"; } </script> <p id="change">New text will replace this.</p> <input type="button" value="Click" onclick="addResult();"/>
  8. 8. 8 Validating forms with JS Form validation Can be performed on client-side or server-side Attach validation function to form's onsubmit handler If validation function returns true, form passes data If false, form does not submit Validation example: form <form name="emailForm" action="submit.php" method="get" onsubmit="return validate();"> Enter your email address: <input type="text" name="address"/> <input type="submit" value="Submit"/> </form> Validation example: script <script type="text/javascript"> function validate() { if (document.emailForm.address.value == "") { alert("Please enter your email address!"); return false; } else { return true; } } </script> Design considerations Server-side vs. client-side Server-side code (PHP) Executes before browser loads page Can interact with external sources (databases, etc) Requires page refresh Client-side code (JavaScript) Executes after page loads Can't directly interact with other sources More responsive, no page refresh needed The two are often useful in combination
  9. 9. 9 Compatibility issues Can't expect JavaScript to work everywhere Different browsers support different features Some users turn JavaScript off Older browsers, non-graphical browsers, mobile browsers, etc… Solution: Provide redundant functionality with PHP PHP works on all browsers Providing alternatives Form validation can be performed both in PHP and JavaScript Use redundant validation Perform JS validation as above Validate in PHP script as well <form name="emailForm" action="submit.php" method="get" onsubmit="return validate();"> Alternatives Links: Provide JS functionality in JavaScript, comparable PHP version as link Non-JS browsers ignore onclick JS browsers return false, don't follow PHP link <a href="phpFunction.php" onclick="jsFunction(); return false;"> Link text</a> Debugging JavaScript JavaScript pages can be run locally in browser No great debugging tools for JS Use Firefox's JavaScript Console to debug your code JavaScript Security Cross Site Scripting (XSS) JS from one domain cannot access pages from another domain No access to file systems JS cannot read data from an external file Code injection Unvalidated user input can inject JS code into a response page Where to get help JavaScript Kit syntax references http://www.javascriptkit.com/jsref/ http://www.javascriptkit.com/domref/ W3Schools JavaScript tutorial http://www.w3schools.com/js/default.asp QuirksMode has information regarding which browsers support which functions http://www.quirksmode.org/
  10. 10. 10 Questions? Pop Quiz What’s the JavaScript syntax for declaring a global variable? 1. global MyVar; 2. global $MyVar 3. var MyVar 4. declare MyVar Pop Quiz What output does the following code produce? function MyFunc(limit) { var step = 2; for (var i = 0; i <= limit; i++) { total = step * i; document.write(total + "<br />"); } } MyFunc(100); test Pop Quiz Which of the following things can JavaScript NOT do? 1. Open new browser windows 2. Change content on the page 3. Read data from an external file 4. Validate user input Pop Quiz True or False? Javascript statements must end with a semi-colon? FALSE Pop Quiz DOM is an acronym for 1. Document Object Model 2. Distributed Object Method 3. Document Orientation Model 4. Data Object Model
  11. 11. 11 Next Overview of extra credit assignment JavaScript lab Advanced JavaScript (Time permitting) Getting user input confirm() allows you to display an OK/Cancel dialog Returns true or false exit = confirm("Are you sure you want to leave?"); if (exit) { /* leave page */ } prompt() allows you to create a pop-up dialog that requests information name = prompt("What is your name"); alert("Hello, " + name + "!"); Passing PHP variables to JS Can pass from PHP to JS using echo <script type="text/javascript"> var address = "http://google.com"; // pass variable "name" from PHP to JS <?php echo "var name = " . $name . ";n"; ?> </script> Passing JS variables to PHP Can set a hidden input using JavaScript <script type="text/javascript"> var size = "giant"; // pass variable "size" to PHP document.form1.size = size; </script> … <form name="form1" action="submit.php"> <input name="size" type="hidden" value=""/> </form> Opening windows with JavaScript The window.open() function can be used to open additional browser windows Syntax: var name = window.open(url, windowName, params) See http://www.javascriptkit.com/javatutors/ window1.shtml
  12. 12. 12 window.open() example <script type="text/javascript"> function openWindow(url) { // we can reference this window with variable 'win' var win = window.open(url, 'win', 'width=600,height=500,status'); } </script> … <a href="win.html" onclick="openWindow('win.html'); return false;">Open window</a>