Introduction to JavaScript DOM and Events

Slides:



Advertisements
Similar presentations
17 HTML, Scripting, and Interactivity Section 17.1 Add an audio file using HTML Create a form using HTML Add text boxes using HTML Add radio buttons and.
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
5.1 JavaScript Execution Environment
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
Lesson 12- Unit L Programming Web Pages with JavaScript.
The Web Warrior Guide to Web Design Technologies
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Cos 381 Day 9.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
JavaScript, Third Edition
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Cos 381 Day 10.
CST JavaScript Validating Form Data with JavaScript.
DHTML - Introduction Introduction to DHTML, the DOM, JS review.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JS: Document Object Model (DOM)
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 JavaScript and HTML Documents.
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
UFCEWT-20-3 Advanced Topics in Web Development Lecture 4 : JavaScript, Browsers & the HTML DOM-API.
DOM and JavaScript Aryo Pinandito.
Lecture 11 – DOM Scripting SFDV3011 – Advanced Web Development Reference: 1.
Section 17.1 Add an audio file using HTML Create a form using HTML Add text boxes using HTML Add radio buttons and check boxes using HTML Add a pull-down.
Parsing with DOM using MSXML Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
JavaScript – The DOM JavaScript is object based The browser is object based – We can access the browser's objects in the same way we did JavaScript's Two.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
JavaScript IV ECT 270 Robin Burke. Outline DOM JS document model review W3C DOM.
Chapter 5: Windows and Frames
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Review of the DOM Node properties and methods Some ways of accessing nodes Appending, copying and removing nodes Event handling – Inline – Scripting –
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Document Object Model. Back to the DOM… Javascript and the DOM  Originally, the Document Object Model (DOM) and Javascript were tightly bound  Each.
Dr. Ahmet Cengizhan Dirican BIL 374 Internet Technologies 5. JavaScript and HTML Documents.
Host Objects: Browsers and the DOM
JS: Document Object Model (DOM) DOM stands for Document Object Model, and allows programmers generic access to: DOM stands for Document Object Model, and.
This is our seminar JavaScript And DOM This is our seminar JavaScript And DOM.
Chapter 10 Dynamic HTML (DHTML) JavaScript, Third Edition.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
Introduction to JavaScript DOM Instructor: Sergey Goldman.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 5 Host Objects: Browsers.
REEM ALMOTIRI Information Technology Department Majmaah University.
THE DOM.
Introduction to.
DHTML.
Chapter 5 Validating Form Data with JavaScript
Programming Web Pages with JavaScript
In this session, you will learn to:
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Introduction to JavaScript Events
Section 17.1 Section 17.2 Add an audio file using HTML
JavaScript Functions.
JavaScript and Events.
Document Object Model (DOM): Objects and Collections
JavaScript and HTML Documents
Introduction to Programming the WWW I
PHP.
Javascript and JQuery SRM DSC.
Introduction to DHTML, the DOM, JS review
Chengyu Sun California State University, Los Angeles
Web Programming and Design
Presentation transcript:

Introduction to JavaScript DOM and Events Instructor: Sergey Goldman

DOM (Document Object Model ) JavaScript attached to HTML like to a canvas DOM to be the single most important skill   Object One document is the page An object is just a thing h1 is an object ul is an object Model Document represented as tree structure. Simplest of HTML contains a head and a body.

DOM cont Gives you scripting access to all the elements on a web page. Using JavaScript, you can create, modify and remove elements in the page dynamically.

Javascript and the DOM Originally, DOM and Javascript were tightly bound Each major browser had their own overlapping DOM implementation jargon: DHTML Now, the DOM is a separate standard, and can be manipulated by other languages (e.g. Java, server side javascript, python, etc.) Browsers still differ in what parts of the standard they support, but things are much better now

Parent-child Not a language but idea, or agreement Objects are in a hierarchy It is the way to reach into the page from the script tags text attributes

VERY important object in any window or frame. The document Object VERY important object in any window or frame. The document object represents a web document or a page in a browser window. When accessing multiple sites simultaneously, there would be multiple windows opened. Each window would have a corresponding window object, and each window object would have its own document object. http://www.w3schools.com/js/js_htmldom_document.asp

The history Object Each time you visit a web page and click on the “Back” or “Forward” arrow buttons on your browser toolbar, you are accessing the history list. You can also add similar buttons/links that allow users to move backward and forward via the information stored in the history object. http://www.w3schools.com/jsref/obj_history.asp

Ex: DOM allows The window is the parent for a given web page document is the child of window with the objects that are most commonly manipulated

Nodes Even a small html has many node

12 Node Types important NodeType Named Constant 1 ELEMENT_NODE 2 ATTRIBUTE_NODE 3 TEXT_NODE 4 CDATA_SECTION_NODE 5 ENTITY_REFERENCE_NODE 6 ENTITY_NODE 7 PROCESSING_INSTRUCTION_NODE 8 COMMENT_NODE 9 DOCUMENT_NODE 10 DOCUMENT_TYPE_NODE 11 DOCUMENT_FRAGMENT_NODE 12 NOTATION_NODE

Element, attribute, text nodes Element nodes: no text Text nodes: text

Objects can be referenced Referencing Objects Objects can be referenced by their id or name this is the easiest way, but a name should be unique in the hierarchy by their numerical position in the hierarchy, by walking the array that contains them by their relation to parent, child, or sibling parentNode previousSibling nextSibling firstChild lastChild childNodes array

Node name and ids The id property sets or returns the id of an element (the value of an element's id attribute). An ID should be unique within a page, and is often used to return the element using the document.getElementById() method. The name attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id attributes, but the same name. When submitted, there is just the one value in the response - the radio button you selected. <input type="checkbox" name="foo" value="1" /> if checked will submit foo=1. In the DOM you can reference form elements from the form.elements collection by specifying the name as the index. If name is not unique, the collection returns an array of elements rather than the element.

Node name and ids cont. Modern DOM's support looking up form elements by name as: document.getElementsByName(nameValue) note: it always returns an array even if only one element is found. id attribute is from the XML world, and is a unique id for any node, not just form elements. Unlike the name attribute it is valid on any HTML node. Also like the name attribute, it must follow the valid identifier rules. The identified should start with an alpha, and only contain alpha ([a-zA-Z]), numbers, hyphen, underscore and colons (note ASP.NET breaks this rule by starting reserved IDs with a underscore - thus they will always fail an HTML/XML lint - actually some proxies strip them). To find any HTML element by id you use: document.getElementById(idvalue)

IDs Should be unique Applied once Class attribute can applied to multiple document.getElementById(“abc”);

12.2 Modeling a Document: DOM Nodes and Trees getElementById method Returns objects called DOM nodes Every piece of an HTML page (elements, attributes, text, etc.) is modeled in the web browser by a DOM node The nodes in a document make up the page’s DOM tree, which describes the relationships among elements Nodes are related to each other through child-parent relationships A node can have multiple children, but only one parent Nodes with the same parent node are referred to as siblings The html node in a DOM tree is called the root node, because it has no parent

Browsers Dev Tools

DOM view Chapter 12 fig12_02 domtree.html (Deitel WWW textbook) Animated: https://developer.chrome.com/devtools/docs/dom-and-styles

Chrome DOM view Elements Console, type window Right Click -> Inspect (<ctrl>+<shift>+<c>) Live-edit: https://developers.google.com/web/tools/chrome-devtools/inspect-styles/?utm_source=dcc&utm_medium=redirect&utm_campaign=2016q3

FF DOM view

12.3 Ex.: Traversing and Modifying a DOM Tree Demo several DOM node features and two additional document-object methods. it allows you to highlight, modify, insert and remove elements. CSS class highlighted is applied dynamically to elements in the document to add, remove and select elements using the form. Manipulate the HTML5 document dynamically by modifying its DOM

IDs are shown, like [para1], [para2], [item1],…

dom.js start document.getElementById( "byIdButton" ).addEventListener("click", byId, false ); function byId() { var id = document.getElementById( "gbi" ).value; var target = document.getElementById( id ); if ( target ) switchTo( target ); } function switchTo( newNode ) currentNode.setAttribute( "class", "" ); // remove old highlighting currentNode = newNode; currentNode.setAttribute( "class", "highlighted" ); // highlight document.getElementById( "gbi" ).value = currentNode.getAttribute( "id" );

12.3 Traversing and Modifying a DOM Tree (Cont.) The JavaScript code declares two variables Variable currentNode keeps track of the currently highlighted node—the functionality of each button depends on which node is currently selected. Variable idcount is used to assign a unique id to any new elements that are created. The remainder of the JavaScript code contains event-handling functions for the buttons and two helper functions that are called by the event handlers.

Func name

addEventListener function Parameter Description event Required. A String that specifies the name of the event. Note: Do not use the "on" prefix. For example, use "click" instead of "onclick". For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference. function Required. Specifies the function to run when the event occurs.  When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. useCapture Optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.  Possible values:true - The event handler is executed in the capturing phase false- Default. The event handler is executed in the bubbling phase

Capture vs Bubble* Events can be activated at two occasions: At the beginning ("capture") - true, and at the end ("bubble") -false. Events are executed in the order of how they're defined. Ex.: window.addEventListener("click", function(){alert(1)}, false); window.addEventListener("click", function(){alert(2)}, true); window.addEventListener("click", function(){alert(3)}, false); window.addEventListener("click", function(){alert(4)}, true); The alert boxes will pop up in this order: 2 (defined first, using capture=true) 4 (defined second using capture=true) 1 (first defined event with capture=false) 3 (second defined event with capture=false)

12.3 Finding and Highlighting an Element getElementById The first row of the form allows the user to enter the id of an element into the text field and click the Get By Id button to find and highlight the element.

12.3 Attribute Manipulation The DOM element methods setAttribute and getAttribute allow you to modify an attribute value and get an attribute value, respectively.

12.3 Traversing and Modifying a DOM Tree (Cont.) document object createElement method Creates a new DOM node, taking the tag name as an argument. It does not insert the element on the page. document object createTextNode method Creates a DOM node that contains only text. Given a string argument, createTextNode inserts the string into the text node. Method appendChild Inserts a child node (passed as an argument) after any existing children of the node on which it’s called Property parentNode contains the node’s parent insertBefore method Inserts newNode as a child of the parent directly before currentNode. replaceChild method Receives as its first argument the new node to insert and as its second argument the node to replace. removeChild method Remove the oldNode (a child of the new currentNode) from its place in the HTML5 document.

document.getElementsByTagName()

12.4 DOM Collections DOM has collections - groups of related objects on a page DOM collections are accessed as properties of DOM objects such as the document object or a DOM node The document object has properties containing the images collection, links collection, forms collection and anchors collection Contain all the elements of the corresponding type on the page The collection’s length property specifies the number of items in the collection

12.4 DOM Collections Access the elements of the collection using indices in square brackets (like array element) item method of a DOM collection An alternative to the square bracketed indices Receives an integer argument and returns the corresponding item in the collection. namedItem method receives an element id as an argument and finds the element with that id in the collection. href property of a DOM link node Refers to the link’s href attribute Collections allow easy access to all elements of a single type in a page Useful for gathering elements into one place and for applying changes across an entire page

DOM Grab, can start anywhere var myTitleLink = document.getElementById("mainTitle"); // information about the node console.log("This is a node of type: ", myTitleLink.nodeType); // 1 ELEMENT_NODE console.log("Inner HTML: ", myTitleLink.innerHTML); //text console.log("Child nodes: ", myTitleLink.childNodes.length); //1   // how many links? var myLinks = document.getElementsByTagName("a"); console.log("Links: ", myLinks.length); // First, grab a div called "homeNav" var navItems = document.getElementById("homeNav"); // narrowing down the links further - use another element, not the whole document. var myLinks = navItems.getElementsByTagName("a"); console.log("Links in navItems: ", myLinks.length); // or even combined var x = document.getElementById("mainNav").getElementsByTagName("a"); console.log("Links in mainNav: ", x.length);

Restricting elements

Changing content/attribute If the attribute doesn't currently exist, it will be created.

innerHTML

Create Element In space

Appending li

Appending text (better way)

Alternative appending

Alternative appending cont

InsertBefore

Ex. Collections

12.5 Dynamic Styles An element’s style can be changed dynamically E.g., in response to user events Can create mouse-hover effects, interactive menus and animations The document object’s body property Refers to the body element The setAttribute method is used to set the style attribute with the user-specified color for the background-color CSS property. If you have predefined CSS style classes defined for your document, you can also use the setAttribute method to set the class attribute.

12.6 Using a Timer and Dynamic Styles to Create Animated Effects setInterval and clearInterval methods to combine them with dynamic styles to create animated effects. This example is a basic image viewer that allows you to select a book cover and view it in a larger size. When the user clicks a thumbnail image, the larger version grows from the top-left corner of the main image area.

setInterval method of the window object 12.6 Using a Timer and Dynamic Styles to Create Animated Effects (Cont.) setInterval method of the window object Repeatedly executes a statement on a certain interval Takes two parameters A statement to execute repeatedly An integer specifying how often to execute it, in milliseconds Returns a unique identifier to keep track of that particular interval. window object’s clearInterval method Stops the repetitive calls of object’s setInterval method Pass to clearInterval the interval identifier that setInterval returned Anonymous function Defined with no name—it’s created in nearly the same way as any other function, but with no identifier after the keyword function.