Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to JavaScript DOM and Events

Similar presentations


Presentation on theme: "Introduction to JavaScript DOM and Events"— Presentation transcript:

1 Introduction to JavaScript DOM and Events
Instructor: Sergey Goldman

2 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.

3 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.

4 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

5 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

6 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.

7 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.

8 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

9 Nodes Even a small html has many node

10 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

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

12 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

13 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.

14 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)

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

16 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

17 Browsers Dev Tools

18

19 DOM view Chapter 12 fig12_02 domtree.html (Deitel WWW textbook)
Animated:

20 Chrome DOM view Elements Console, type window
Right Click -> Inspect (<ctrl>+<shift>+<c>) Live-edit:

21 FF DOM view

22

23 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

24

25

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

27

28

29 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" );

30 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.

31 Func name

32 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

33 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)

34

35

36

37

38 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.

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

40 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.

41

42

43

44

45

46 document.getElementsByTagName()

47 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

48 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

49 DOM Grab, can start anywhere
var myTitleLink = document.getElementById("mainTitle"); // information about the node console.log("This is a node of type: ", myTitleLink.nodeType); // 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);

50 Restricting elements

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

52 innerHTML

53 Create Element In space

54 Appending li

55 Appending text (better way)

56 Alternative appending

57 Alternative appending cont

58 InsertBefore

59 Ex. Collections

60

61

62

63 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.

64

65

66

67 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.

68

69

70

71

72

73

74

75

76

77

78 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.


Download ppt "Introduction to JavaScript DOM and Events"

Similar presentations


Ads by Google