Javascript Elements Client-Side Scripting Why Use Client
Client-side scripting
JavaScript Elements
• client-side script: code runs in browser a"er page is sent back from server – often this code manipulates the page or responds to user actions
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 2
Why use client-side programming? What is JavaScript?
• PHP already allows us to create dynamic web pages. Why • a lightweight programming language ("scripting language") also use client-side scripting? • • Client-side scripting (JavaScript) benefits: used to make web pages interactive – – usability: can modify a page without having to post back to the server insert dynamic text into HTML (ex: user name) (faster UI) – react to events (ex: page load user click) – efficiency: can make small, quick changes to page without wai?ng for – get information about a user's computer (ex: browser type) server – perform calculations on user's computer (ex: form validation) – event-driven: can respond to user ac?ons like clicks and key presses • a web standard (but not supported identically by all • Server-side programming (PHP) benefits: browsers) – security: has access to server's private data; client can't see source code – compa7bility: not subject to browser compa?bility issues • NOT related to Java other than by name and some syntactic – power: can write files, open connec?ons to servers, connect to databases, ... similarities
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 3 4
Short History of JavaScript JavaScript and JAVA • Originally developed by Netscape, as LiveScript • JavaScript and Java are only related through syntax • Javascript is interpreted • Became a joint venture of Netscape and Sun in • JAVA is strongly typed - types are known at compile time and 1995, renamed JavaScript operand types (τύποι τελεστέων) are checked for • Now standardized by the European Computer compatibility Manufacturers Association as ECMA-262 (also • Variables in JavaScript are dynamically typed ISO 16262) – Compile-time type checking impossible • JavaScript has more relaxed syntax and rules • We’ll call collections of JavaScript code scripts, – fewer and "looser" data types not programs – variables don't need to be declared – errors often silent (few exceptions)
http://www.ecma-international.org/publications/standards/Ecma-262.htm 5 6 JavaScript vs. Java JavaScript vs. PHP
• interpreted, not compiled • similarities: – • more relaxed syntax and rules both are interpreted, not compiled – fewer and "looser" data types + = – both are relaxed about syntax, rules, and types – variables don't need to be declared – both are case-sensitive – errors often silent (few exceptions) – both have built-in regular expressions for powerful text processing • key construct is the function rather than the class • differences: – "first-class" functions are used in many situations – JS is more object-oriented: noun.verb(), less • contained within a web page and integrates with its HTML/ procedural: verb(noun) CSS content – JS focuses on UIs and interacting with a document; PHP on • Objects in: HTML output and files/forms – – JAVA are static: their collection of data members and methods JS code runs on the client's browser; PHP code runs on the web server is fixed at compile time – JavaScript are dynamic: members of an object can change
during execution Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 7 8
Overview of JavaScript Object Orientation and JavaScript
• JavaScript can be used to: • JavaScript is NOT an object-oriented programming – replace some of what is typically done with applets (except language graphics) – Does not support class-based inheritance - cannot support – replace some of what is done with CGI - namely server-side polymorphism programming (but no file operations or networking) – Has prototype-based inheritance, which is much different • User interactions through forms are easy • JavaScript objects are collections of properties, which • The Document Object Model makes it possible to support are like the members of classes in Java and C++ dynamic HTML documents with JavaScript • JavaScript has primitives for simple types – Much of what we will do with JavaScript is event-driven computation
9 10
Linking to a JavaScript file: script
• script tag should be placed in HTML page's head • script code is stored in a separate .js file • JS code can be placed directly in the HTML file's body or head (like CSS) Linking JavaScript to HTML – but this is bad style (should separate content, presentation, and behavior)
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 12 JavaScript in HTML body (example) Browsers and HTML/JavaScript Documents
• What happens when the browser encounters a JavaScript script in a document?
• JS code can be embedded within your HTML • Two approaches for embedding JavaScript in HTML page's head or body documents: – Explicit embedding (ρητή ενσωμάτωση) • runs as the page is loading – mixes HTML content and JS scripts (bad) – Implicit embedding (υπόρρητη ενσωμάτωση) – can cause your page not to validate
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 13 14
Implicit vs Explicit JavaScript JavaScript embedding
• Explicit embedding: • Scripts are usually hidden from browsers that do – Mixes two types of notation inside the same document (bad for readability) not include JavaScript interpreters by putting – Makes maintenance difficult - often different people manage the them in special comments: HTML and the JavaScript – The head of an HTML document - for scripts that produce • This is also required by the HTML validator content only upon request or for those that react to user interactions • Note that the comment closure is in a new line • These scripts contain function definitions and code associated with form and is also a JS comment elements – The body of an HTML document - for scripts that are to be interpreted just once, as they are found
15 16
Event-driven programming
• JS programs have no main; they respond to user actions called events • Event-driven programming: writing programs driven by user events Events in JavaScript • To respond to events, we can write code to respond to various events as the user generates them : event handlers
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 18 Event-driven programming A simple JavaScript Program
• To respond to an event in JavaScript, we follow the following • Problem: create a page with a button that will cause some steps: code to run when it is clicked. – decide which element or control we want to respond to • Step 1: create the HTML Control – write a JavaScript function with the code we want to run (event – button's text appears inside tag; can also contain images handler) – attach that function to the control’s event
Javascript example • Event handlers typically cause some sort of change to be
made to the web page: –
changing text on the page – dynamically adjusting styles of elements on the page – adding/removing content from the page • Step 2: Write JavaScript Event-Handling Function: – Need to add code to take action when button is clicked – Create a JS file with a function to execute when button is clicked function sayMagicWord() { alert(“PLEASE!”); Event Handler 19 } 20
Pop-up messages in JS A simple JavaScript Program
• JavaScript has three methods for creating dialog boxes: • Step 3: Attach Event Handler to Control – alert, confirm, and prompt – connect JS file to HTML file, using
• type attribute it optional in HTML5; used for backward compatibility • script typically contains no inner content, but not allowed to be a self- closing tag
– attach the sayMagicWord JS function to the click of the button • Every HTML element has special event attributes that represent actions you can perform on it: onclick, onkeydown, onchange, onsubmit • To attach a handler that will “listen” to an event on an element, you set a value for one of the element’s event attributes, which points to the event handler
…
21 22
Javascript example
– Note: sayMagicWord executes when the user clicks the button, not when the page is loaded
23 24 No Javascript?
Javascript example
99 100
function Point(xValue, yValue) { Modifying built-in prototypes this.x = xValue; this.y = yValue; Point.prototype.distanceFrom = function(x2, y2) { var d1 = this.x - x2; var d2 = this.y - y2; alert("DistanceFrom:" + this.x + " " + this.y); return Math.sqrt(d1 * d1 + d2 * d2); } ; } function compute() { alert("compute"); var x1 = document.getElementById("x1").value; var y1 = document.getElementById("y1").value; alert("DistanceFrom:" + x1 + " " + y1); } ANY prototype can be modified, including those of existing var p1 = new Point(x1,y1); var x2 = document.getElementById("x2").value; types var y2 = document.getElementById("y2").value; var answer = document.getElementById("answer"); } Prototype and other libraries do this answer.innerHTML = p1.distanceFrom(x2, y2); } } not quite the same as adding something to a single object
} Exercise: Add a reverse method to strings. } Exercise: Add a shuffle method to arrays.
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 101 102 9.1: Global DOM Objects
• 9.1: Global DOM Objects • 9.2: DOM Element Objects • 9.3: The DOM Tree JavaScript and DOM
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 103 104
The six global DOM objects The window object
• Every Javascript program can refer to the following global • Represents the entire browser window; the top-level object in objects: DOM hierarchy – technically, all global code and variables become part of the object name description window document current HTML page and its content • Properties: history list of pages the user has visited • document, history, location, name location URL of the current HTML page • methods: – navigator info about the web browser you are using alert, confirm, prompt (popup boxes) – setInterval, setTimeout clearInterval, clearTimeout (timers) screen info about the screen area occupied by the browser – open(URL, name, options), close (popping up new browser windows) window the browser window • blur, focus, moveBy(dx, dy), moveTo(x,y), print, resizeBy, resizeTo, scrollBy, scrollTo 105 106
Popup windows with window.open The document object
window.open("http://foo.com/bar.html", "My Foo • Represents the current web page and the elements inside it Window", • Properties: "width=900,height=600,scrollbars=1"); – anchors (array), body (DOM element), cookie JS (string), domain (string), forms (array), images (array), links, referrer (string), title (string), URL • window.open pops up a new browser window (string) • methods: • THIS method is the cause of all the terrible popups on the web! – getElementById – getElementsByName, getElementsByTagName • some popup blocker software will prevent this method from – querySelector, querySelectorAll running – close, open, write, writeln
107 108 The location object The navigator object
• the URL of the current web page • information about the web browser application • properties: • properties: – host, hostname, href, pathname, port, protocol, – appName, appVersion, browserLanguage, cookieEnabled, platf search, hash orm, userAgent • methods: • Some web programmers examine the navigator object to – assign, reload, replace see what browser is being used, and write browser-specific http://www.example.com:8080/foo/bar/index.html?a=b&c=d#link05 scripts and hacks: • The assign() method loads a new document. if (navigator.appName === "Microsoft Internet Explorer") { ... JS • The difference between this method and replace(), is that – this is poor style; you usually do not need to do this replace() removes the URL of the current document from the – browsers’ features keep changing document history, meaning that it is not possible to use the – user can set her browser to “spoof” its app name to any string "back" button to navigate back to the original document. they want – better approach: check for specific JS objects and features
109 110
The screen object The history object
• information about the client's display screen • the list of sites the browser has visited in this window • properties: • properties: – availHeight, availWidth, colorDepth, height, pixelDepth, width – length • methods: – back, forward, go(index) • sometimes the browser won't let scripts view history properties, for security reasons
• JavaScript event code seen previously was obtrusive, in the • this is bad style (HTML is cluttered with JS code) HTML; this is bad style • goal: remove all JavaScript code from the HTML body • now we'll see how to write unobtrusive JavaScript code – HTML with minimal JavaScript inside HTML – uses the DOM to attach and execute all JavaScript functions // called when OK button is clicked • allows separation of web site into 3 major categories: function okayClick() { alert("booyah"); – content (HTML) - what is it? } JS – presenta7on (CSS) - how does it look? – behavior (JavaScript) - how does it respond to user interac?on? output
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 113 114 Attaching an event handler in JavaScript code When does my code run?
• it is legal to attach event handlers to elements' DOM objects • your file's JS code runs the moment the browser loads in your JavaScript code the script tag – any variables are declared immediately – notice that you do not put parentheses after the function's – any functions are declared but not called, unless your global code name explicitly calls them • this is better style than attaching them in the HTML • at this point in time, the browser has not yet read your • Where should we put the code below? page's body – none of the DOM objects for tags on the page have been created yet
objectName.onevent = function; JS
HTML var okButton = document.getElementById("ok"); ... HTML okButton.onclick = okayClick; JS var x = 3; function f(n) { return n + 1; } function g(n) { return n - 1; } Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst x = f(x); JS 115 116
A failed attempt at being unobtrusive The window.onload event
• problem: global JS code runs the moment the script is • we want to attach our event handlers right after the page is loaded done loading • script in head is processed before page's body has loaded – there is a global event called window.onload event that – no elements are available yet or can be accessed yet via the occurs at that moment DOM • in window.onload handler we attach all the other handlers • we need a way to attach the handler after the page has to run when events occur loaded... function functionName() { // code to initialize the page
... } HTML // run this function once the page has finished loading window.onload = functionName; var ok = document.getElementById("ok"); ok.onclick = okayClick; // error: null JS Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 117 118
An unobtrusive event handler Common unobtrusive JS errors
• many students mistakenly write () when attaching the handler
– our JSLint checker will catch this mistake • event names are all lowercase, not capitalized like most variables
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 119 120 Anonymous functions Anonymous function example
• JavaScript allows you to declare anonymous func7ons • quickly creates a function without giving it a name • can be stored as a variable, attached as an event handler, etc.
• or the following is also legal (though harder to read and bad style):
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 121 122
9.2: DOM Element Objects Complex DOM manipulation problems
• 9.1: Global DOM Objects • How would we do each of the following in JavaScript code? • 9.2: DOM Element Objects Each involves modifying each one of a group of elements ... • 9.3: The DOM Tree • When the Go button is clicked, reposition all the divs of class puzzle to random x/y locations. • When the user hovers over the maze boundary, turn all maze walls red. • Change every other item in the ul list with id of TAs to have a gray background.
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 123 124
The DOM tree Types of DOM nodes
• element nodes (HTML tag) – can have children and/or attributes • text nodes (text in a block element) • aOribute nodes (attribute/value pair) – text/attributes are children in an element node – • The elements of a page are nested into a tree-like structure cannot have children or attributes of objects – not usually shown when drawing the DOM tree – the DOM has properties and methods for traversing this tree
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 125 126 DOM object properties DOM Properties for form Controls
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 127 128
Modifying text inside an element Abuse of innerHTML
• DOM element objects have the following properties: • innerHTML can inject arbitrary HTML content into the page • innerHTML : text and/or HTML tags inside a node • however, this is prone to bugs and errors and is considered • : text (no HTML tags) inside a node textContent poor style – simpler than innerHTML, but not supported in IE6 • we forbid using innerHTML to inject HTML tags; inject plain • value : the value inside a form control text only – (later, we'll see a better way to inject content with HTML tags in it)
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 129 130
Adjusting styles with the DOM Common DOM styling errors
• many students forget to write .style when setting styles
• style properties are capitalized likeThis, not like-this
• style properties must be set as strings, often with units at the end • contains same properties as in CSS, but with camelCasedNames – examples: backgroundColor, borderLeftWidth, fontFamily • write exactly the value you would have written in the CSS, but in quotes
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 131 132 Unobtrusive styling 9.3: The DOM Tree
• 9.1: Global DOM Objects • 9.2: DOM Element Objects • 9.3: The DOM Tree • well-written JavaScript code should contain as little CSS as possible • use JS to set CSS classes/IDs on elements • define the styles of those classes/IDs in your CSS file
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 133 134
Traversing the DOM tree DOM tree traversal example
• Every node's DOM object has the following properties:
• complete list of DOM node properties • browser incompatiblity information (IE6 sucks)
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 135 136
Element vs. text nodes Selecting groups of DOM objects
• methods in document and other DOM objects (* = HTML5):
• Q: How many children does the div above have? • A: 3 – an element node representing the
– two text nodes representing "\n\t" (before/after the paragraph) • Q: How many children does the paragraph have? The a tag?
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 137 138 Getting all elements of a certain type Complex selectors
• highlight all paragraphs in the document: • highlight all paragraphs inside of the section with ID "address":
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 139 140
Creating new nodes Modifying the DOM tree
} Every DOM element object has these methods:
• merely creating a node does not add it to the page • you must add the new node as a child of an existing element on the page... } A paragraph! } A paragraph! } A paragraph! } A paragraph! } A paragraph! Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 141 142
Removing a node from the page DOM versus innerHTML hacking
• Why not just code the previous example this way?
• each DOM object has a removeChild method to remove its children from the page
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst 143 144