• Like


Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Uploaded on


More in: Technology , Design
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    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

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


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