Web Design. Lecture 6. Instructor : Cristina Mîndruță Site : https://sites.google.com/site/webdescm. Cristina Mindruta - Web Design

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

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

JavaScript Handling Events Page 1

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

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

Photo from DOM

JavaScript: Events, the DOM Tree, jquery and Timing

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

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

Catching Events. Bok, Jong Soon

CITS3403 Agile Web Development Semester 1, 2018

JavaScript and Events

CSE 154 LECTURE 10: MORE EVENTS

CS193X: Web Programming Fundamentals

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

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

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

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

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

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

Web Site Development with HTML/JavaScrip

CSE 154 LECTURE 10: THE DOM TREE

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

AJAX: The Basics CISC 282 March 25, 2014

AJAX: The Basics CISC 282 November 22, 2017

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

729G26 Interaction Programming. Lecture 4

CSC Web Programming. JavaScript Browser Objects

Events: another simple example

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

JavaScript: Events, DOM and Attaching Handlers

5/19/2015. Objectives. JavaScript, Sixth Edition. Using Touch Events and Pointer Events. Creating a Drag-and Drop Application with Mouse Events

B. V. Patel Institute of Business Management, Computer and Information Technology, UTU. B. C. A (3 rd Semester) Teaching Schedule

Touch Forward. Bill Fisher. #touchfwd. Developing Awesome Cross-Browser Touch

Session 6. JavaScript Part 1. Reading

DOM Primer Part 2. Contents

Fundamentals of Website Development

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

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

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

INDEX SYMBOLS See also

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

CSC Javascript

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

20480C: Programming in HTML5 with JavaScript and CSS3. Course Code: 20480C; Duration: 5 days; Instructor-led. JavaScript code.

Session 16. JavaScript Part 1. Reading

CE212 Web Application Programming Part 2

Document Object Model. Overview

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

Document Object Model (DOM)

1. Cascading Style Sheet and JavaScript

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

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

JavaScript: The Definitive Guide

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

Interactor Tree. Edith Law & Mike Terry

Chapter 11 Objectives

Sections and Articles

Web Development. With PHP. Web Development With PHP

[MS-POINTER]: Microsoft Edge / Internet Explorer Pointer Events Standards Support Document

Using JavaScript for Client-Side Behavior

Skyway Builder Web Control Guide

CISC 1600 Lecture 2.4 Introduction to JavaScript

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

Ajax. Ronald J. Glotzbach

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

Index. Boolean value, 282

JavaScript CS 4640 Programming Languages for Web Applications

COURSE OUTLINE MOC 20480: PROGRAMMING IN HTML5 WITH JAVASCRIPT AND CSS3

The DOM and jquery functions and selectors. Lesson 3

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

TEXTAREA NN 2 IE 3 DOM 1

Web Programming Step by Step

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

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

Tizen Web UI Technologies (Tizen Ver. 2.3)

[MS-DOM4]: Microsoft Edge / Internet Explorer DOM4 Standards Support Document

DOM Interface subset 1/ 2

XML: Introduction. !important Declaration... 9:11 #FIXED... 7:5 #IMPLIED... 7:5 #REQUIRED... Directive... 9:11

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

The course also includes an overview of some of the most popular frameworks that you will most likely encounter in your real work environments.

JavaScript Programming

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

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript Specialist v2.0 Exam 1D0-735

Introduction to Automation. What is automation testing Advantages of Automation Testing How to learn any automation tool Types of Automation tools

JQuery WHY DIDN T WE LEARN THIS EARLIER??!

JavaScript II CSCI 311 SPRING 2017

JSF. JSF and Ajax Basics

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

DATABASE SYSTEMS. Introduction to web programming. Database Systems Course, 2016

Index LICENSED PRODUCT NOT FOR RESALE

XML: Tools and Extensions

An updated events syntax for XML-based markup languages

PHP / MYSQL DURATION: 2 MONTHS

jquery Cookbook jquery Community Experts O'REILLY8 Tokyo Taipei Sebastopol Beijing Cambridge Farnham Koln

Web Design & Dev. Combo. By Alabian Solutions Ltd , 2016

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

Cleveland State University Department of Electrical and Computer Engineering. CIS 408: Internet Computing

skb2 Shaon Barman, Sarah Chasins, Ras Bodik UC Berkeley Sumit Gulwani Microsoft Research

Transcription:

Web Design Lecture 6 Instructor : Cristina Mîndruță Site : https://sites.google.com/site/webdescm

Topics JavaScript in Web Browsers The Window Object Scripting Documents Scripting CSS Handling Events

JS (Java Scripting) HTML structural layer CSS presentational layer JS behavioral layer React to user input altering the contents of the page, the CSS styles, the browser s behavior Create highly responsive interfaces that improve the user experience and provide dynamic functionality, without waiting for the server to load up a new page.

DOM Document Object Model Document Object Model (DOM) - the fundamental API for representing and manipulating the content of HTML and XML documents. nested elements of an HTML/XML document are represented in the DOM as a tree of objects. <html> <head> <title>sample Document</title> </head> <body> <h1>an HTML Document</h1> <p>this is a <i>simple</i> document </body> </html>

DOM (Document Object Model) Types of nodes: Element node (HTML tag) can have children and/or attributes Text node (text in a block element) Attribute node (attribute/value pair) Text and attribute nodes children in an element node cannot have children or attributes <p> This is a paragraph of text with a <a href="/path/page.html">link in it</a>. </p>

DOM Document Object Model Node type hierarchy:

DOM Document Object Model Global variable document refers the Document object. Element objects HTML elements in the Document object. Element objects are selected by: id attribute (unique in the document) document.getelementbyid("element_id") type (tag name) document.getelementsbytagname("tag_name"); element.getelementsbytagname("tag_name"); returns a live NodeList object that behaves like a read-only array of Element objects. shortcut properties to access certain kinds of nodes: body, head, images, forms, links, embeds, plugins, scripts HTML object collections (ex. document.forms), which are similar to NodeList objects, and can additionally be indexed by element ID or name.

DOM Document Object Model Element objects are selected by (cont.): class(es) getelementsbyclassname("class_name") returns live NodeList containing all matching descendants of the document or element. CSS selector queryselector() / queryselectorall() - takes a single string argument containing a CSS selector and returns the first element that matches the selector / a static NodeList that represents all elements in the document that match the selector. OBS. jquery library uses CSS selector-based query as its central programming paradigm. Web applications based on jquery use a portable, cross-browser equivalent to queryselectorall() named $().

DOM Document structure and traversal Node type - defines properties for traversing DOM tree. parentnode - null for nodes that have no parent (ex. Document object). childnodes live NodeList, read-only array-like object firstchild, lastchild nextsibling, previoussibling - connect nodes in a doubly linked list. nodetype - Document nodes have the value 9. Element, 1. Text nodes, 3. Comments nodes, 8 and DocumentFragment nodes, 11. nodevalue - textual content of a Text or Comment node. nodename - tag name of an Element, converted to uppercase. // second child node of the first child of the Document document.childnodes[0].childnodes[1] document.firstchild.firstchild.nextsibling

DOM Document structure and traversal Documents can be also traversed as trees of only Element objects, ignoring Text and Comment nodes, using the following attributes: Attributes on Node objects: children - live NodeList, read-only array-like object firstelementchild, lastelementchild nextelementsibling, previouselementsibling childelementcount, children.length

DOM Attributes HTML attributes HTMLElement and its subtypes define properties that correspond to the standard attributes of HTML elements. HTMLElement defines properties for the universal HTTP attributes (id, title lang, dir) event handler properties (ex. onclick). Element-specific subtypes define attributes specific to those elements. Non-HTML attributes Element type also defines getattribute(), setattribute(), hasattribute() and removeattribute() methods Attributes as nodes attributes (property on Node) : live, read-only array-like object elementnode.attributes[index] or element.attributes.attrname returns Attr object with properties name and value. var image = document.getelementbyid("myimage"); var imgurl = image.src;

DOM Attributes Dataset attributes: data attributes and the Dataset API introduced by HTML 5. Valid dataset attribute = any attribute whose name is lowercase and begins with the prefix data Standard way to attach additional data without compromising document validity. Programmer-defined attributes : data attrname Accessible through dataset property of element : document.getelementbyid("elementid").dataset Dataset - object containing name-value pairs where name is attrname <span id="opt" data course="web Design" data credits="4" ></span> var dat = document.getelementbyid("opt").dataset dat object is: { course: "Web Design", credits "4" }

DOM Element content Element properties for accessing / modifying element content : as HTML: ex. This is a <i>simple</i> document. innerhtml : the content of that element including markup outerhtml includes the opening and closing tags of the element insertadjacenthtml() as plain text : ex. This is a simple document. textcontent = straightforward concatenation of all Text node descendants of the specified element.

DOM Operations with Nodes Creating Node objects: document.createelement( tagname ) document.createtextnode("textnodecontent") document.createdocumentfragment() anothernode.clonenode() Inserting Node objects: appendchild(newchildnode) insertbefore(newchildnode, existingchildnode) Deleting, and replacing Node objects: removechild(existingchildnode) replacechild(existingchildnode, newchildnode) : removes one child node and replaces it with a new one.

DOM HTML Forms document.forms HTML Collection object that allows form elements to be selected by numerical order, by id, or by name. document.forms.formid, document.forms.formname document.forms[formposition] Form object Properties: formobject.elements [ ] - array with all elements in the form action, encoding, method, target are attributes of the <form> element Methods: submit(), reset() Events: onsubmit, onreset

DOM HTML Forms Form element object Common properties: type form read-only reference to the containing form object name value - the string that is sent to the web server when the form is submitted Specific properties; radio / checkbox element: checked, defaultchecked select element: type, selectedindex, selected, text, options.length Events: onclick: button, reset, submit, checkbox, radio onchange: checkbox, radio, select, text, textarea, password, file focus / blur : all types (receive / lose focus) onkeypress, onkeydown, onkeyup, oninput text elements

Topics JavaScript in Web Browsers The Window Object Scripting Documents Scripting CSS Handling Events

CSS Cascading Style Sheets (CSS) - standard for specifying the visual presentation of HTML documents CSS styles can be scripted => scripted visual effects

CSS Scripting style attribute of individual document elements. style - property of Element object only for inline styles element.style.styleattribute = "value"; Ex: e.style.fontsize = "24pt" using strings for the whole style declaration e.setattribute("style", s); s = e.getattribute("style"); e.style.csstext = s; s = e.style.csstext; getcomputedstyle(element, pseudo) gets all the actual (computed) CSS property and values of the specified element, i.e. the style actually used in displaying the element, after styling from multiple sources have been applied. element the element to get a styling for pseudo pseudo-selector like hover or null if not needed. returns CSSStyleDeclaration object : collection of CSS property-value pairs. More details: http://javascript.info/tutorial/styles-and-classes-getcomputedstyle#style

CSS Scripting style attribute of individual document elements. Managing element classes: classlist property of Element object; live; read-only array-like object add() / remove() - add / remove individual class names toggle() - adds/removes a class name contains() - tests whether the class attribute contains a specified class name.

CSS Scripting style sheets document.stylesheets property- read-only array-like object containing CSSStyleSheet objects (represent the stylesheets associated with the document) disabled property of <style>, <link> elements, and CSSStyleSheet objects. CSSStyleSheet object cssrules[] array contains CSSRule objects (the rules of the stylesheet) CSSRule object properties: selectortext style - writable CSSStyleDeclaration object insertrule(), deleterule() methods

Topics JavaScript in Web Browsers The Window Object Scripting Documents Scripting CSS Handling Events

Handling events JS - asynchronous event-driven programming model. Web browser generates* an event whenever something interesting happens to the document or browser or to some element or object associated with it. JS application can register to one event type one or more functions to be invoked when events of that type occur. event type (name) - name to identify the specific kind of event. event target - object on which the event occurred or with which the event is associated. event handler (event listener) - function that handles (responds to) an event. Applications register their event handler functions with the web browser, specifying an event type and an event target. * fires, triggers, or dispatches

Handling events Event object object associated with a particular event contains details about that event is passed as an argument to the event handler function Properties : type, target, other, specific to each event type Default actions are associated with some event types.

Handling events Event categories Device-dependent input events - directly tied to a specific input device (keyboard, mouse, touch screen) Device-independent input events - not directly tied to a specific input device. (ex. click, textinput event ) User interface events - higher-level events, often on HTML <form> elements that define a user interface for a web application. (focus, change value, submit) State-change events - triggered by network or browser activity, and indicating state-related change. (load, DOMContentLoaded, online, offline, readystatechange, loadstart, progress, loadend ) API-specific events - web APIs defined by HTML5 and related specifications (events in drag-and-drop API, events on <video> and <audio> elements) Timers and errors - part of client-side JavaScript s asynchronous programming model, are similar to events.

Registering event handlers A. By setting a property, on the object or document element that is the event target, to the desired event handler function. Event handler properties : onevent set an event /media/user/comun/cursuri/webdesign/curs/curs6/ig_6.html handler property in JS code set directly as HTML attribute targetobject.onevent = function(){...}; function funcname() {... } targetobject.onevent = funcname; // Set the onload property of the Window object to a function. // The function is the event handler: it is invoked when the document loads. window.onload = function() {...} // Look up a <form> element var elt = document.getelementbyid("shipping_address"); // Register an event handler function that will be invoked right // before the form is submitted. elt.onsubmit = function() { return validate(this); } <button onclick="alert('thank you');">click Here</button> Example

Registering event handlers B. Defining EventListener (on any object that can be an event target). addeventlistener(eventtype, handlerfunction, false) On the same object, more handlers can be registered for the same event type; invoked in the order they were registered. <button id="mybutton">click me</button> <script> var b = document.getelementbyid("mybutton"); b.onclick = function() { alert("thanks for clicking me!"); }; b.addeventlistener("click", function() { alert("thanks again!"); }, false); </script> removeeventlistener(eventtype, handlerfunction, false)

Event handlers invocation mechanism Event handlers - automatically invoked by the browser, based on the event type and target. Event object the argument at invocation; has the attribute type. Invocation context - the object on which event handlers are defined (this keyword refers to the event target). Event handler is invoked as method of the target object. Event handler - executed in the scope in which is defined, not the scope from which is invoked. Event handlers registered as HTML attributes run with a modified scope chain: direct access to global variables and to properties of some special objects: target object, the containing <form> object (if there is one), and the Document object.

Handling events event propagation Propagation path propagation of the Event object from the browser. Event target chain Capture phase: Event object propagates through the target's ancestors from the defaultview to the target's parent. Event listeners registered for this phase handle the event before it reaches its target. addeventlistener(eventtype, handlerfunction, true) Bubble phase: Event object propagates through the target's ancestors in reverse order, starting with the target's parent and ending with the defaultview. Event listeners registered for this phase handle the event after it has reached its target. Target phase: Event object arrives at the event object's event target. Event listeners registered for this phase handle the event once it has reached its target. If the event type indicates that the event must not bubble, the event object halts after completion of this phase.

Handling events event propagation Consequence of event bubbling: register a single handler on a common ancestor element and handle events there. Ex. Register an change handler on a <form> element instead of registering a change handler for every element in the form. Event capturing (reverse bubbling) provides an opportunity to peek at events before they are delivered to their target. A capturing event handler can be used for debugging, or it can be used along with an event cancellation technique to filter events so that the target event handlers are never actually invoked. event.preventdefault() - cancel the default action for an event event.returnvalue = false event.stoppropagation() - prevents the propagation of the event to any other objects. event.stopimmediatepropagation() - prevents the propagation of the event to any other objects and also prevents the invocation of any other event handlers registered on the same object.

Events Document events: load - document and all of its related files are fully loaded DOMContentLoaded - fired when the document has been loaded and parsed and any deferred scripts have been executed. Images and async scripts may still be loading, but the document is ready to be manipulated. Mouse events: click, contextmenu, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout. Event properties: clientx and clienty - coordinates of the mouse pointer relative to the containing window. altkey, ctrlkey, metakey, shiftkey - keyboard modifier keys held down when the event occurred. button - which mouse button. Complete list at : http://www.w3schools.com/jsref/dom_obj_event.asp

Events Drag and Drop events: https://html.spec.whatwg.org/#dnd drag source and drop target may be in the same application or in different applications. Draggable element: draggable attribute set event listener for dragstart that stores the data being dragged. Drop target checks that it's not a text selection that is being dragged stores data into the DataTransfer object set the allowed effects (copy, move, link, or some combination). dropzone attribute - what kind of data to accept and what kind of feedback to give event listener for drop event. Example explained at : http://www.w3schools.com/html/html5_draganddrop.asp

Keyboard events: keydown, keypress, keyup Event properties: keycode Touchscreen events: Events altkey, ctrlkey, metakey, shiftkey - keyboard modifier keys held down when the event occurred. touchstart, touchend, touchmove, touchcancel Event properties: changedtouches - array-like object : position of each touch. scale - ratio of the current distance between the two fingers to the initial distance between the fingers ( pinch close < 1.0; pinch open > 1.0.) rotation - the angle of finger rotation since the start of the event (clockwise rotation: angle in degrees > 0). Pointer Events - Recommendation http://www.w3.org/tr/2015/rec-pointerevents-20150224/ Defines events and related interfaces for handling hardware agnostic pointer input from devices including mouse, pen, touchscreen, etc.

JS - Execution JavaScript idealized execution mechanism 1. Creates a Document object and begins parsing the web page, adding Element objects and Text nodes to the document as it parses HTML elements and their textual content. The document.readystate property has the value loading. 2. When the HTML parser encounters <script> elements that have neither the async nor defer attributes, it adds those elements to the document and then executes the inline or external script. These scripts are executed synchronously, and the parser pauses while the script downloads (if necessary) and runs. Scripts like these can use document.write() to insert text into the input stream. That text will become part of the document when the parser resumes. Synchronous scripts often simply define functions and register event handlers for later use, but they can traverse and manipulate the document tree as it exists when they run. That is, synchronous scripts can see their own <script> element and document content that comes before it. 3. When encountered a <script> element that has the async attribute set, it begins downloading the script text and continues parsing the document. The script will be executed as soon as possible after it has downloaded, but the parser does not stop and wait for it to download. Asynchronous scripts must not use the document.write() method. They can see their own <script> element and all document elements that come before it, and may or may not have access to additional document content.

JS - Execution JavaScript idealized execution mechanism (cont.) 4. When the document is completely parsed, the document.readystate property changes to interactive. 5. Any scripts that had the defer attribute set are executed, in the order in which they appeared in the document. Async scripts may also be executed at this time. Deferred scripts have access to the complete document tree and must not use the document.write() method. 6. The browser fires a DOMContentLoaded event on the Document object. This marks the transition from synchronous script execution phase to the asynchronous eventdriven phase of program execution. Note, however, that there may still be async scripts that have not yet executed at this point. 7. The document is completely parsed, but the browser may still be waiting for additional content, such as images, to load. When all such content finishes loading, and when all async scripts have loaded and executed, the document.readystate property changes to complete and the web browser fires a load event on the Window object. 8. From this point on, event handlers are invoked asynchronously in response to user input events, network events, timer expirations, and so on.

Bibliography David Flanagan, Java Script. The Definitive Guide. 6-th ed., O'Reilly 2011 Jennifer Niederst Robbins, Learning Web Design, Fourth Edition, O Reilly Media, 2012 Robin Nixon, Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition A Stepby-Step Guide to Creating Dynamic Websites, Publisher: O'Reilly Media, 2012 http://www.ecma-international.org/publications/files/ecma-st/ecma-262.pdf www.w3schools.com http://www.w3.org/standards/webdesign/ www.w3.org/tr/html5/ https://developer.mozilla.org/en-us/docs/web/guide/html/html5