Photo from DOM

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

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

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

DOM Primer Part 2. Contents

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

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

Events: another simple example

Fundamentals of Website Development

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

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

Overview. Event Handling. Introduction. Reviewing the load Event. Event mousemove and the event Object. Rollovers with mouseover and mouseout

Skyway Builder Web Control Guide

Introduction to DHTML

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

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

JavaScript Handling Events Page 1

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

CITS3403 Agile Web Development Semester 1, 2018

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

JavaScript and Events

Introduction to using HTML to design webpages

TEXTAREA NN 2 IE 3 DOM 1

Hell is other browsers - Sartre. The touch events. Peter-Paul Koch (ppk) WebExpo, 24 September 2010

Best Practices Chapter 5

Produced by. App Development & Modeling. BSc in Applied Computing. Eamonn de Leastar

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

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

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

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

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

729G26 Interaction Programming. Lecture 4

Session 16. JavaScript Part 1. Reading

CSC Javascript

Continues the Technical Activities Originated in the WAP Forum

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

Web Design. Lecture 6. Instructor : Cristina Mîndruță Site : Cristina Mindruta - Web Design

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

Web Site Development with HTML/JavaScrip

HCDE 530: Computational Techniques for HCDE Data Visualization in Web, Part 2

Session 6. JavaScript Part 1. Reading

CSC Web Programming. JavaScript Browser Objects

Forms, Form Events, and Validation. Bok, Jong Soon

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

1. Cascading Style Sheet and JavaScript

PIC 40A. Midterm 1 Review

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

CST272 Getting Started Page 1

Hell is other browsers - Sartre. The touch events. Peter-Paul Koch (ppk) DIBI, 28 April 2010

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

DC71 INTERNET APPLICATIONS JUNE 2013

JavaScript: Events, the DOM Tree, jquery and Timing

Client-side Techniques. Client-side Techniques HTML/XHTML. Static web pages, Interactive web page: without depending on interaction with a server

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

COMS 359: Interactive Media

Installation and Configuration Manual

Catching Events. Bok, Jong Soon

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

JSF - H:SELECTONERADIO

Information Design. Professor Danne Woo! infodesign.dannewoo.com! ARTS 269 Fall 2018 Friday 10:00PM 1:50PM I-Building 212

LAB MANUAL SUBJECT: WEB TECHNOLOGY CLASS : T.E (COMPUTER) SEMESTER: VI

Lesson 5 Introduction to Cascading Style Sheets

Name Related Elements Type Default Depr. DTD Comment

NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS

Cascading style sheets, HTML, DOM and Javascript

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 14 Test Bank

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

of numbers, converting into strings, of objects creating, sorting, scrolling images using, sorting, elements of object

extc Web Developer Rapid Web Application Development and Ajax Framework Using Ajax

Design patterns and Animation with jquery. with Paul Bakaus

JavaScript: Events, DOM and Attaching Handlers

CE212 Web Application Programming Part 2

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

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

JAVASCRIPT FOR PROGRAMMERS

Mouse-over Effects. Text based buttons

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

Ajax in Practice by Dave Crane Bear Bibeault Jord Sonneveld with Ted Goddard, Chris Gray, Ram Venkataraman and Joe Walker

CSE 154 LECTURE 10: MORE EVENTS

JSF - H:SELECTONEMENU

Web Designing Course

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

jquery Tutorial for Beginners: Nothing But the Goods

CITS1231 Web Technologies

JSF - H:PANELGRID. JSF Tag. Rendered Output. Tag Attributes. The h:panel tag renders an HTML "table" element. Attribute & Description.

Web Development & Design Foundations with HTML5

ITEC447 Web Projects CHAPTER 9 FORMS 1

JQuery WHY DIDN T WE LEARN THIS EARLIER??!

Javascript Lecture 23

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

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

JSF. JSF and Ajax Basics

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

MooTools 1.2. Jacob Gube Garrick Cheung. Chapter No. 5 "Working with Events"

XHTML Mobile Profile. Candidate Version Feb Open Mobile Alliance OMA-TS-XHTMLMP-V1_ C

WEB DESIGNING COURSE SYLLABUS

JavaScript II CSCI 311 SPRING 2017

Proper_Name Final Exam December 21, 2005 CS-081/Vickery Page 1 of 4


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

HTML5. HTML5 Introduction. Form Input Types. Semantic Elements. Form Attributes. Form Elements. Month Number Range Search Tel Url Time Week

Transcription:

Photo from http://www.flickr.com/photos/emraya/2861149369/ DOM

2 DOM When a browser reads an HTML file, it must interpret the file and render it onscreen. This process is sophisticated. Fetch Parse Flow Paint URL Cac he Tree Display List Pix els The HTML file is turned into a "tree" object. This object is named 'document' and it is a DOM instance. graphics from Yahoos Douglas Crockford.

3 DOM The DOM is a model of the HTML document. Standardized by w3c A document-processing library of objects and function. In other words, an API Standards DOM 0 is supported by all JavaScript enabled browsers but has no specification. DOM 1 was released in 1998 DOM 2 was released in 2000 DOM 3 was released in 2004 DOM 4 is the latest approved standard

4 DOM Why the DOM? Since the HTML file is an 'object', it can be processed and changed by JavaScript functions. This supports user interaction with a web page. "Dynamic HTML" is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated. Flow Paint Script Event graphics from Yahoos Douglas Crockford.

5

6 TREES AND NODES

7 TREES AND NODES

8 TREES AND NODES

9 DOM The DOM specification defines a set of classes that all browsers are expected to support. The browsers implement the specification in JavaScript The DOM classes and methods are JavaScript objects and methods These objects and methods are used to programmatically control an HTML document. There are several globally defined variables in a browserbased JavaScript environment along with numerous globally defined methods. document window

10 DOM SUMMARY

11 DOM SUMMARY Every JS environment in a browser defines a global variable named document. This variable is of Document type.

12 FINDING AN ELEMENT You can write code to retrieve element(s) in the document By id var node = document.getelementbyid('x13'); By class var nodes = document.getelementsbyclassname('well'); By tag var nodes = document.getelementsbytagname('div'); By name (the attribute) var nodes = document.getelementsbyname('movies'); By CSS selector var node = document.queryselector(.btn ); // the first var nodes = document.queryselectorall(.btn ); // all

13 READING/WRITING ATTRIBUTES Elements have attributes that can be read and changed. node.getattribute( propname ) node.setattribute(propname, propvalue); Examples var node = document.getelementbyid( x13 ); var id = node.getattribute( id ); node.setattribute( 'style', 'background-color:red;'); node.setattribute( 'id', id + 3 );

14 CREATING NODES IN THE DOM You can create nodes and insert them into the document. Note that there is a difference between an HTML element and a text-node. document.createelement( tagname ) document.createtextnode( text ) Example: var node = document.createelement( tr ); var cell= document.createelement( td ); var cellvalue = document.createtextnode( 13 );

15 ADDING NODES TO THE DOCUMENT The new nodes are not part of the document. They have simply been created. Insert them using one of the following methods. node.appendchild( newnode ) node.insertbefore(newnode, newnodessibling ) Example: var node = document.createelement( tr ); var cell= document.createelement( td ); var cellvalue = document.createtextnode( 13 ); cell.appendchild( cellvalue ); node.appendchild( cell ); node.insertbefore( otherrow, cell )

16 DELETING NODES FROM A DOCUMENT Node replacement is possible via node.replacechild( newnode, oldchild ) Example var node = document.getelementbyid( x13 ); var newnode = document.createelement( div ); node.parentnode.replacechild( newnode, node ); How to delete a node in the DOM node.removenode(childnodetoremove) It is often helpful to take a chunk of HTML and replace it by some other chunk of HTML. This can be done by node.innerhtml = newhtmltext.

17 NAME DIFFERENCES WITH STYLING CSS background-color border-radius font-size list-style-type word-spacing z-index JavaScript backgroundcolor borderradius fontsize liststyletype wordspacing zindex

18 DOM EXAMPLES Write a function to return all the siblings that follow an element Write a function to return all of the children of an element Write a function to return all of the ancestors of an element. Write a function that accepts a UL element and a list of strings. Insert the strings into the list. Write a function to create and return a multiplication table covering the rows [1, M] and the columns [1,N]. M and N are parameters.

19 EXAMPLE Write a page that uses JS to create a page having a single ordered-list of several NFL team names.

20 THE JS CODE

21 DOCUMENT READY The JS file executes as soon as the code is loaded. This may occur before the containing HTML is fully loaded This may occur before the HTML is parsed This means that the names element is not present when the line document.getelementbyid( names ) is executed. Most pages register a handler to execute on page-load. document.addeventlistener( DOMContentLoaded, f ); $(document).ready( f ); // if using jquery. Function f is then executed only after the HTML page has been loaded AND parsed. Can also move the script to the bottom of the page This is not a guarantee that the doc is parsed This assumes synchronous loads (not always the case)

22 EVENTS AND HANDLING An event is a user-or-browser generated action. Events are of specific types. Events are typically associated with an HTML element When an event occurs, one-or-more JavaScript functions will be called Event categories Mouse events Keyboard events HTML frame/object events HTML form events User interface events Mutation events (changes to the structure of a document)

23 EVENT HANDLERS Elements may generate events when they are acted upon. clicking on a button pressing a key in an input field hovering over an element entering an element with the mouse many others. Handlers are associated with events in one of two ways Using HTML : <div onclick="divclicked(event)">i'm a button!</div> Using JS: node["on" + type] = handlerfunction; node.addeventlistener(<event-type>, <func>, <capture>); <event-type> is a string <func> is the event handler <capture> is a boolean indicating capture phase (true) or bubble

24 EVENT HANDLING PROCESS Target node: the node that generates/creates the event Capturing phase : Events begin at the root and move toward the target node Registered and enabled event handlers at nodes on the path from root-to-target are executed when encountered Target phase: Registered handlers at the target are executed Bubbling phase: The tree is traversed from target to root. Registered and enabled handlers at nodes on the path are executed when encountered. Default phase : Default handlers are invoked

25 EVENT PHASES Capture (Phase 1) Bubble (Phase 3) E1 E2 Target (Phase 2) E3 When the target element (E3) is clicked 1. Any E1 Capture-enabled click-handlers are executed 2. Any E2 Capture-enabled click-handlers are executed 3. Any E3 Capture-enabled click-handlers are executed 4. Any E3 bubble-enabled click-handlers are executed 5. Any E2 bubble-enabled click-handlers are executed 6. Any E1 bubble-enabled click-handlers are executed 7. Any default click-handlers are executed

26 EVENT OBJECTS An event object has the following read-only properties bubbles : a boolean cancelable : a boolean target : the target node currenttarget : the element whose handler is executing defaultprevented : a boolean eventphase : a string denoting processing phase timestamp : the time the event was created Event objects also support the following methods preventdefault() : cancels the event stoppropagation() : prevents further handler invocation

27 EVENTS click Type (JS) onclick Attribute (HTML) Description Bubbles Cancelable Fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is: mousedown, mouseup, click dblclick ondblclick Fires when the pointing device button is double clicked over an element Yes Yes mousedown onmousedown Fires when the pointing device button is pressed over an element Yes Yes mouseup onmouseup Fires when the pointing device button is released over an element Yes Yes mouseover onmouseover Fires when the pointing device is moved onto an element Yes Yes mousemove onmousemove Fires when the pointing device is moved while it is over an element Yes No mouseout onmouseout Fires when the pointing device is moved away from an element Yes Yes Yes Yes Type Attribute Description Bubbles Cancelable select onselect Fires when a user selects some text in a text field, including input and textarea Yes No change onchange Fires when a control loses the input focus and its value has been modified since gaining focus Yes No submit onsubmit Fires when a form is submitted Yes Yes reset onreset Fires when a form is reset Yes No focus onfocus Fires when an element receives focus either via the pointing device or by tab navigation No No blur onblur Fires when an element loses focus either via the pointing device or by tabbing navigation No No http://en.wikipedia.org/wiki/dom_events

28 EXAMPLE : TOGGLE SWITCH Write code (HTML/CSS/JS) to support a toggle-switch component A toggle switch Has two states: on and off Is a picture of those states. red = off, blue = on. clicking anywhere on the toggle-switch changes the state. Start with the HTML <div class= toggle-switch ></div>

29 GETTING INPUT VALUES Recall that input elements gather user input. How to obtain the value of an input element? text type: x.value checkbox type: x.checked radio type: x.checked color type: x.value (A string of form #RRGGBB) date type : x.value (A string of form YYYY-MM-DD) Examples: var x = document.getelementbyid('a').value; var y = document.getelementbyid('b').checked;

30 JAVASCRIPT DOM METHODS Several JavaScript methods support modal dialogs. alert(text) : no return value confirm(text) : return a boolean prompt(text, default) : returns the value entered or null.

31 JAVASCRIPT DOM METHODS Asynchronous function execution settimeout( f, t ) : execute f after t milliseconds. Returns a handle that can be used to stop the function. setinterval( f, t ) : execute f every t milliseconds. Returns a handle that can be used to stop the function. clearinterval( handle ) cleartimeout( handle ); Examples var p = function() { print('hello'); } var x = setinterval( p, 2500); clearinterval( x ); var x = settimeout( p, 2500 ); cleartimeout( x );

32 CREATING A PAGE Write a web page that turns a JavaScript array of NFL teams into an ordered list of HTML strings on the page. An NFL team has properties name : a string city : a string conference : NFC, AFC division : EAST, WEST, CENTRAL Modify to order by conference Modify to order by division

33 DOM EVENTS EXAMPLE Develop an HTML page that allows users to order a pizza. Use onclick handling for the radio buttons Users must select one topping Sardines Anchovies Lemons Pumpernickel Users must select one cheese Provolone American Blue Cheddar Some combinations of topping/cheese are so repugnant that it would be unethical to sell them. Users receive a warning if selecting unethical combinations. The selection is nonetheless allowed on the page. Sardines and Cheddar Pumpernickel and Blue Lemons and Blue Alternately, warn and disallow unethical combinations