JavaScript: A Crash Course

Similar documents
LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

Events: another simple example

JavaScript Handling Events Page 1

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

JavaScript: Events, the DOM Tree, jquery and Timing

Android Programming: Overview

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

The Prototype Framework Part III: Better OOP

CSC Javascript

Fundamentals of Website Development

HTML User Interface Controls. Interactive HTML user interfaces. Document Object Model (DOM)

jquery Ajax Support: Sending Data to the Server

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

JavaScript: Getting Started

JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming

Introduction to DHTML

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

Photo from DOM

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

Want to add cool effects like rollovers and pop-up windows?

Name Related Elements Type Default Depr. DTD Comment

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

JavaScript: Functions

Session 7. JavaScript Part 2. W3C DOM Reading and Reference

Simplifying GWT RPC with

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

JavaScript II CSCI 311 SPRING 2017

The Google Web Toolkit (GWT):

JavaScript: Events, DOM and Attaching Handlers

Outline. Lecture 4: Document Object Model (DOM) What is DOM Traversal and Modification Events and Event Handling

CSE 154 LECTURE 10: MORE EVENTS

The Google Web Toolkit (GWT):

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

JSF: The "h" Library Originals of Slides and Source Code for Examples:

Session 6. JavaScript Part 1. Reading

Advanced Features. venues, or customized versions can be held on-site at your organization.

Web Site Development with HTML/JavaScrip

DOM Primer Part 2. Contents

Session 16. JavaScript Part 1. Reading

Installation and Configuration Manual

EECS1012. Net-centric Introduction to Computing. Lecture JavaScript Events

Best Practices Chapter 5

Skyway Builder Web Control Guide

Javascript. Many examples from Kyle Simpson: Scope and Closures

Web Programming Step by Step

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Lecture : 3. Practical : 2. Course Credit. Tutorial : 0. Total : 5. Course Learning Outcomes

JSF - H:INPUTSECRET. Class name of a validator that s created and attached to a component

jquery Tutorial for Beginners: Nothing But the Goods

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

Jakarta Struts: An MVC Framework

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

Canvas & Brush Reference. Source: stock.xchng, Maarten Uilenbroek

Setup and Getting Startedt Customized Java EE Training:

Javascript Hierarchy Objects Object Properties Methods Event Handlers. onload onunload onblur onfocus

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

Chapter 14. Dynamic HTML: Event Model

Introduction to using HTML to design webpages

Web Designing Course

JS Tutorial 3: InnerHTML Note: this part is in last week s tutorial as well, but will be included in this week s lab

1$ 5 ! $ 6 4 * Source: 0 "!*! 0! * 8 97 ?!$ 5 0 *! 4! $ 0 : * ' () 7;7 7<7

Rich Interfaces with jquery UI: Part 1 Setup and Basic Widgets

CS Final Exam Review Suggestions - Spring 2018

CICS 515 a Internet Programming Week 3. Mike Feeley

JavaScript Introduction

The Google Web Toolkit (GWT): Extended GUI Widgets

Unobtrusive JavaScript. Lecture Outline. CSE 190 M (Web Programming), Spring 2008 University of Washington

Client vs Server Scripting

Java with Eclipse: Setup & Getting Started

UNIT - III. Every element in a document tree refers to a Node object. Some nodes of the tree are

CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM

File I/O in Java 7: A Very Quick Summary

JavaScript Specialist v2.0 Exam 1D0-735

Place User-Defined Functions in the HEAD Section

Developed and taught by well-known Contact author and developer. At public for details venues or onsite at your location.

Student, Perfect Final Exam May 25, 2006 ID: Exam No CS-081/Vickery Page 1 of 6

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Library Part II: Visual Effects

New Media Production Lecture 7 Javascript

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

Index. Ray Nicholus 2016 R. Nicholus, Beyond jquery, DOI /

Web Development & Design Foundations with HTML5

CISC 1600 Lecture 2.4 Introduction to JavaScript

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

5. Strict mode use strict ; 6. Statement without semicolon, with semicolon 7. Keywords 8. Variables var keyword and global scope variable 9.

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

5/19/2015. Objectives. JavaScript, Sixth Edition. Understanding the Browser Object Model and the Document Object Model. Objectives (cont'd.

Table Basics. The structure of an table

CITS3403 Agile Web Development Semester 1, 2018

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

Programing for Digital Media EE1707. Lecture 4 JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

JavaScript 3. Working with the Document Object Model (DOM) and DHTML

TEXTAREA NN 2 IE 3 DOM 1

The first sample. What is JavaScript?

HTML TAG SUMMARY HTML REFERENCE 18 TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES MOST TAGS

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

CSC Web Programming. JavaScript Browser Objects

Transcription:

2010 Marty Hall JavaScript: A Crash Course Part III: Browser-Specific Features Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/ajax.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2010 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t / Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Courses developed d and taught by Marty Hall Java 6, servlets/jsp (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics Ajax courses Customized can concentrate Java on 1 EE library Training: (jquery, Prototype/Scriptaculous, http://courses.coreservlets.com/ Ext-JS, Dojo, Google Closure) or survey several Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, Spring, JSP, JSF Hibernate/JPA, 2.0, Struts, EJB3, Ajax, Web GWT Services, 2.0, Ruby/Rails Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known Contact author hall@coreservlets.com and developer. At public for details venues or onsite at your location.

Topics in This Section Manipulating the DOM Finding elements of interest Inserting HTML into existing elements Reading textfield values And other input elements Assigning event handlers Directly in the HTML From JavaScript, p, via window.onload HTML-specific classes 5 2010 Marty Hall Intro Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Main Points Most important topics How to insert HTML into a page document.getelementbyid( ).innerhtml = ; How to read a textfield value escape(document.getelementbyid( ).value); How to assign an event handler <input onclick="somefunctioncall()"/> This goes in the HTML page someelement.onclick = somefunction; This is done directly in JavaScript, probably from the window.onload handler. 7» This section cover a lot of other topics, and unless you have JavaScript experience already, you won t follow all of it. But, for most Ajax applications, the topics above are by far the most important ones. Browser-Specific Classes 8 Previous two lectures Described general JavaScript syntax and capabilities i This lecture Describes JavaScript specifically for browser applications Next lecture Describes JavaScript capabilities for parsing XML Reminder re references Online http://www.w3schools.com/js/ http://www.w3schools.com/htmldom/dom_reference.asp http://www.devguru.com/technologies/ecmascript/ QuickRef/javascript_intro.html Book JavaScript, the Definitive Guide by David Flanagan

2010 Marty Hall Manipulating the DOM Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Summary Most important topics How to find the element that has a given id var element = document.getelementbyid("..."); How to insert HTML into a page element.innerhtml = " "; You can insert into all sorts of elements (div, span, p, h1, td, etc.). But, be sure that t what you insert would have been legal l if it had been placed there to begin with. So, don t try to insert block-level elements (like h1) into inline elements (like span). Auxiliary topics Finding HTML elements by name Finding all HTML elements of a certain type General info that represents entire page (URL, title, etc.) 10

HTMLDocument Class Overview Obtain reference with predefined document variable Specialized subclass of the Document class that will be discussed in XML lecture Properties title, domain, URL Info about the page. document.url is same as window.location.href unless redirection occurs body The body element anchors, applets, forms, images, links Arrays of subelements, in the order they appear in the document. Usually better to find elements by ids. cookie, lastmodified, referrer In Ajax, it is usually better to manipulate these on server. Notice it is document.referrer, even though the HTTP header is Referer. blah Element that has name="blah" (first one if name repeated) 11 HTMLDocument: Methods 12 getelementbyid Finds element with specified id attribute write, writeln Dynamically insert text into document Used from <script> tag that has body content Not used by Ajax response handlers Use HTMLElement.innerHTML property instead getelementsbyname Returns array of elements that have given name attribute getelementsbytagname Returns array of elements that have given element name Case insensitive Inherited from Document class (see XML lecture)

HTMLElement 13 Subclass of Element class. Obtain with document.body, document.getelementsbytagname, g document.getelementsbyname, document.images. etc. otherelement.getelementsbytagname, otherelement.childnodes, otherelement.firstchild, etc. Most important properties id The id attribute nodename Element name (inherited from Node class). name The name attribute (for HTML elements with "name" only) innerhtml Read/write property p giving g HTML text inside element style CSS2Properties object representing element styling classname Space-separated p list of CSS class names Method scrollintoview Scrolls browser so element is visible The Selectors API W3C defined API for search based on CSS Find a single element that matches CSS selector Find all elements that match CSS selector or selectors Details at http://www.w3.org/tr/selectors-api/ w3 Supported by Firefox 3.5 and recent Chrome releases Main two methods document.queryselector document.queryselectorall See jquery lectures for details & examples jquery used this approach before W3C API existed For speed, jquery now uses native methods if browser supports them 14

2010 Marty Hall Reading Values of Input Elements Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Form Class Obtaining reference document.forms array, form variable for code invoked by input element Any method or property that returns Node (getelementbyid, childnodes, etc.) Properties elements Array of all input elements in form action, enctype, method, name, target Corresponds to HTML attributes Methods submit, reset 16

Image Class Obtaining reference document.images array, document.nameofimage Any method or property that returns Node (getelementbyid, childnodes, etc.) Properties src Read/write property. Changing this changes the image. Preload images first with new Image(...) and setting its href, so browser will have images cached. name, align, alt, border, height, hspace, ismap, usemap, vspace, width Corresponds to HTML attributes Inherited ones described earlier Node, Element, HTMLElement 17 Input Class 18 Obtaining reference theform.elements hf array Any method or property that returns Node (getelementbyid, childnodes, etc.) Properties name, id, value, type, disabled, form (enclosing form) For all input elements defaultvalue Initial value as given in the HTML Type-specific properties (see online API) checked, maxlength, usemap, etc. Methods blur/focus (all), click (buttons, checkboxes, radio buttons), select (file, password, text)

2010 Marty Hall The Window Class Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Idea General information about the page History, URL, status line But does not refer to the DOM (use document for that) Most important for Ajax window.onload = somefunction; Code to run on startup window.setinterval(somefunction, milliseconds); Code to run periodically window.alert("some message") Message to go in popup dialog box. You can just use alert instead of window.alert. 20

Window Class 21 Obtaining reference Use window (or self ) Properties history History object. Not writable. location Location object. To redirect browser, use location.href = "new address"; status Status line value. Read/write. Size/position/scrolling innerwidth, innerheight, outerwidth, outerheight, screenx (or screenleft), screeny (or screentop) Window Class: Methods 22 alert, confirm, prompt Pops up dialog boxes of various sorts print Invokes print dialog setinterval, clearinterval [repeated actions] setinterval(somefunction, milliseconds) settimeout, cleartimeout [one-time actions] settimeout(somefunction, milliseconds) getcomputedstyle Get style info for specified element Movement Lots of methods for opening, closing, resizing windows

Window Class: The onload Event Handler Idea Code to run after the page is loaded. You can t directly do the following in the JavaScript file that is loaded in the head: document.getelementbyid("someid").innerhtml = "some HTML"; document.getelementbyid("someid").onclick = somefunction; The reason is that that DOM does not exist yet, so you can t find the elements and manipulate them. General form window.onload onload = function() { codetorunafterpageloads(); Details See later section on event handling 23 2010 Marty Hall Event Handling Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Idea 25 Most HTML elements have onblah attributes Designates function to run when specified event occurs General event handlers onclick, ondblclick li User single-clicks or double-clicks over element onkeydown, onkeypress, onkeyup User presses key when element has the focus onmousedown, onmouseup User presses mouse over element onmouseover, onmouseout Mouse moves over or leaves being over element onmousemove Mouse moves while over element 26 Approaches to Assigning Event Handlers Assign to property directly in HTML <input type="button" onclick="somefunctioncall()"/> Note the parens: this is a function call Inside the function, this refers to the window Assign to properly indirectly var element = document.getelementbyid("blah"); element.onclick = somefunctionname; Note: no parens: this is a function value. Inside the function, this refers to the element. This process often done from window.onload Use addeventhandler or attachevent DOM 2: addeventhandler; IE: attachevent Lack of portability makes this approach hard to manage

Pros and Cons of Event- Handling Approaches Assigning to property directly in HTML <input onclick="somefunctioncall()"/> Simpler, especially for beginners Slightly easier to pass arguments to the handler Assigning to property indirectly someelement.onclick = somefunctionname; Better separation: all JavaScript in JS files. HTML file contains only HTML. This approach is sometimes known as unobtrusive JavaScript. More work to set up unless you use a JavaScript library like Prototype or jquery. Using window.onload is tricky (see later slides). Slightly more work to pass arguments to function (use anonymous function) 27 Example Code: Directly Assigning Event Handler JavaScript function makeuppercase(textfield) { textfield.value = textfield.value.touppercase(); HTML <input type="text" onkeyup="makeuppercase(this)"/> 28

Example Output: Directly Assigning Event Handler Input was Hello (not HELLO ) 29 Example Code: Indirectly Assigning Event Handler JavaScript function makeuppercase(textfield) { textfield.value = textfield.value.touppercase(); function makemeuppercase() { makeuppercase(this); See slide near end about making window.onload safer when loading multiple JavaScript libraries. window.onload = function() { document.getelementbyid("uppercase-field").onkeyup y p = makemeuppercase; HTML <input type="text" id="uppercase-field"/> 30

Example Output: Indirectly Assigning Event Handler Input was This Is a Test (not THIS IS A TEST ) 31 32 Passing Events to Event Handlers Idea JavaScript automatically passes an event object as the last argument to event handler functions Although you had to use window.event in old IE versions Sometimes you need the event object for extra info General event.type ( click, mouseover, etc.) event.target (element on which event occurred) Mouse events event.button (0 = left, 1 = middle, 2 = right) event.altkey, event.ctrlkey, event.metakey, event.shiftkey» Booleans indicating if keys were down when mouse event occurred event.clientx, tx event.clienty, ty event.screenx, event.screeny Keyboard events event.charcode, event.keycode (see later example)

Keyboard Events (onkeypress) 33 Internet Explorer Use event argument in newer versions Use window.event in older versions event.charcode is numeric character code For printable characters, convert to character with String.fromCharCode Other browsers Use event in all versions event.charcode is numeric character code if character was printable Convert to character with String.fromCharCode event.keycode is numeric character code if character was nonprintable (arrow, ENTER, Control, etc.) You must compare to numeric values here Example: Portable Character Checking Goal Recognize when Down Arrow is pressed When pressed, do whatever pushbutton would have done Main ideas Define handler to take event as argument Use event if defined, otherwise window.event Use charcode if defined, otherwise keycode Don t repeat code: programmatically look up the button s onclick handler and call it 34

Example JavaScript: Portable Character Checking function showvalue(inputid, resultid) { var html = "<div class='sample'>" + document.getelementbyid(inputid).value + "</div>" document.getelementbyid(resultid).innerhtml = html; 35 function doonclickof(buttonid, event) { var e = event e window.event; e var code = e.charcode e.keycode; if (code == 40) { // 40 is Down Arrow var f = document.getelementbyid(buttonid).onclick; f(); Example JavaScript: Portable Character Checking <form action="#"> <label for="textfield-1"> Sample Text (Hit Down Arrow or Press Button): </label> <input type="text" text id="textfield-1" size="40" onkeyup="doonclickof('button-1', event)"/><br/> <input type="button" id="button-1" value="show Sample" onclick="showvalue('textfield-1', 'div-1')"/><br/> / <div id="div-1"></div> </form> 36

Example Output: Portable Character Checking 37 Mouse Events 38 Can capture mouse events on any element Images, links, input elements, even normal text Event Properties To access properties, use event handler that takes event as final argument. To support old browsers, use window.event if event undefined, as in previous example altkey, ctrlkey, metakey, shiftkey Booleans that tell if key was down when event occurred button 0 for left button, 1 for middle, 2 for right clientx, clienty The x and y coordinates relative to the browser window screenx, screeny The x and y coordinates relative to the user s monitor

Mouse Event Handlers: Example (JavaScript) function on(event) { var e = event window.event; var message = "<ul class='sample'>" + " <li>clientx: " + e.clientx + "</li>" + " <li>clienty: " + e.clienty + "</li>" + " <li>screenx: " + e.screenx + "</li>" + " <li>screeny: " + e.screeny + "</li>" + "</ul>"; var region = document.getelementbyid("messageregion"); region.innerhtml = message; 39 function off() { var region = document.getelementbyid("messageregion"); tel tb ") region.innerhtml = ""; Mouse Event Handlers: Example (HTML) <fieldset> <legend>using onclick on Arbitrary Elements</legend> <h2 onclick="alert('ouch!')"> Here is a heading. What happens when you click on it? </h2> </fieldset> <p/> <fieldset> <legend>using onmouseover and onmouseout</legend> <h2 onmouseover="on(event)" onmouseout="off()"> Here is a heading. What happens when you move over it? </h2> <div id="messageregion"></div> </fieldset> 40

Mouse Event Handlers: Example (Results) 41 Specialized Event Handlers 42 input onclick For pushbuttons and toggle buttons. Also fires when button is invoked via keyboard. onchange For textfields, when change is committed (focus leaves) Use onkeyup for individual characters onblur, onfocus form onsubmit, onreset Return false to prevent form from really being submitted. Widely used for client-side validation of form fields. body onblur, onerror, onfocus, onload, onresize, onunload img onabort, onerror, onload

Specialized Event Handlers: window.onloadonload Purpose Run JavaScript code after page is done loading. Used to insert HTML in certain regions or to attach event handlers to certain HTML elements. Neither can be done until page is done loading Simple example (myfile.js) window.onload = function() { document.getelementbyid(" ").onclick = ; document.getelementbyid(" ").innerhtml = ; 43 44 window.onload and Multiple JavaScript Libraries Problem Assigning directly to window.onload replaces any existing window.onload function. Another library might already be using window.onloadonload Solution See if window.onload exists. On Firefox, if no window.onload (typeof window.onload == "undefined") On IE, if no window.onload, onload window.onloadonload is null Either way, you can test!window.onload If so, grab the function var oldwindowloadfunction d df = window.onload; d And call it before your window.onload functions oldwindowloadfunction();

Safer window.onload if (!window.onload) { window.onload onload = function() { document.getelementbyid(" ").onclick = ; document.getelementbyid(" ").innerhtml = ; ; else { var oldwindowloadfunction = window.onload; window.onload = function() { oldwindowloadfunction(); document.getelementbyid(" ").onclick = ; document.getelementbyid(" ").innerhtml = ; ; 45 Additional window.onload Problem Problem window.onload runs after the entire page (including images and style sheets) have been loaded. You have to wait until the DOM is parsed, but you shouldn thaveto have to wait until after the images have been loaded. Solutions Use window.addeventlistener or window.attachevent But it is tricky to make this portable across browsers Many JavaScript libraries (including Prototype and jquery) have simple methods for defining code that runs after the DOM is loaded, but before images and style sheets are loaded d 46

Summary Manipulating the DOM var someelement = document.getelementbyid(" "); Many ways to find elements other than by id someelement.innerhtml =" ; "; Reading textfield values var val = someelement.value; Assigning event handlers <input type="button" onclick="somefunctioncall()"/> 47 window.onload = function() { document.getelementbyid(" ").onclick tel tb ") li = somefunction; 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.