DOM and Events


Published on

Explains DOM and Events. HTML-Only DOM is explained and Form elements.
Events handling using element properties and event listeners is explained too.
A quick review on Cookies and referrer is briefed too

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • document.documentElement.nodeType 1document.documentElement.nodeName "HTML"document.documentElement.tagName "HTML”The HTML element has two children—the head and the body elements. You can access them using the childNodes array-like collection.document.documentElement.childNodes[1].parentNode
  • var bd= document.documentElement;bd.childNodes[1].attributes[0].nodeNamebd.childNodes[1].attributes[0].nodeValuebd.childNodes[1].attributes['class'].nodeValuebd.childNodes[1].getAttribute('class’)
  • var bd= document.documentElement;bd.childNodes[1].attributes[0].nodeNamebd.childNodes[1].attributes[0].nodeValuebd.childNodes[1].attributes['class'].nodeValuebd.childNodes[1].getAttribute('class’)
  • currentStyleruntimeStyle objects to retrieve style works with IE only
  • When may this be undesirable? When the DOM nodes has event handlers attached to it.
  • N.B. This way is actually better because it helps you keep your <div> clean of any JavaScript code.
  • Style property accesses only inline style of element.The DOM provides a way to access an element’s style values: the getComputedStyle() function. IE does also: the element.currentStyle property.
  • cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current web page.
  • cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current web page.
  • the name/value pair you stored is included in the list of cookies for the document. Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape( ) function to encode the value before storing it in the cookie. If you do this, you'll have to use the corresponding unescape( ) function when you read the cookie value.
  • DOM and Events

    1. 1. Lecture Outline DOM Accessing and Modifying DOM Events, revisited HTML-Only DOM Form Elements and Events
    2. 2. DOM The Document Object Model represents the browser as a node tree (parent, child, and sibling). Types of Nodes:  Element Nodes  Text Nodes  Attribute Nodes  Comment Nodes
    3. 3. HTML Example <html>  <head><title>Sample Document</title></head>  <body>  <h1>An HTML Document</h1>  <p>This is a <i>simple</i>document</p>  </body> </html>
    4. 4. The DOM representation of the example
    5. 5. <p title="a gentle reminder">Don‟tforget to buy this stuff.</p>,
    6. 6. Accessing DOM Nodes All nodes have  nodeType,  nodeName (mostly are tag names),  nodeValue (for text nodes; the value is the actual text) window.document: access to the current document.  documentElement: the root node <html>  childNodes:  In order to tell if a node has any children you use hasChildNodes(): true/false  childNodes[] array to access child nodes of any element, has all array properties.  parentNode:  Provided to child to access its parent
    7. 7. childNodes Vs. children .children is a property of an Element. Only Elements have children, and these children are all of type Element. .childNodes is a property of Node. .childNodes can contain any node.
    8. 8. Accessing DOM Nodes window.document (Cont’d):  attributes  In order to tell if a node has any attributes you use hasAttributes()  true/false  attributes[] array to access all attribute nodes of any element, has all array properties  getAttribute(attrname)  to get a certain attribute by name .  Each attribute node has nodeName and nodeValue
    9. 9. <html><head><title>Mypage</title></head><body> <p class="opener"> first paragraph var bd=document.documentElement. </p> children[1]; <p>  bd.childNodes.length =??? 9 <em>second</em> paragraph  bd.childNodes[1].hasAttributes() </p> =?? true <p id="closer">final</p> <!-- and thats about it -->  bd.childNodes[1].getAttribute(class) =???? “opener”</body></html>
    10. 10. Accessing the Content Inside a Tag After reaching a desired node, you may need to get the text/HTML contained in the node by using the properties.  innerText - textContent  innerHTML (to change content of Element nodes only)  nodeValue (this changes value of any node) It sets and gets the content of the element as text or as HTML.
    11. 11. A Shortcut to DOM elements document.getElementById(id)  returns an object representing element or null if not found document.getElementsByTagName(tag)  returns a collection of objects with the specified tag name or [] an empty array if not found document.getElementsByName(name)  returns a collection of objects with the specified name attribute or [] an empty array if not found Shortcut to body element:  document.body
    12. 12. More on Attributes Once you retrieved an Element you can get/set its attributes through  .attributes[index]  .attributes[name]  .getAttribute()/setAttribute  .attributeName  document.getElementsByTagName(p)[2].id  document.getElementsByTagName(p)[2].className
    13. 13. A Shortcut to DOM elements document.getElementById(id)  returns an object representing element or null if not found document.getElementsByTagName(tag)  returns a collection of objects with the specified tag name or [] an empty array if not found document.getElementsByName(name)  returns a collection of objects with the specified name attribute or [] an empty array if not found
    14. 14. Modifying Style Most of the element nodes have a style property, which in turn has a property mapped to each CSS property. Example:  var my = document.getElementById(’mydiv);  = "1px solid red"; CSS properties have dashes but in JavaScript map their names to properties by skipping the dash and uppercase the next letter.  padding-top  paddingTop, margin-left  marginLeft…..
    15. 15. Modifying Style (Cont‟d) You can change the css class using the className property or setAttribute() function. Example:  var m=document.getElementById(„mydiv‟);  m.className=“errorclass”; OR  m.setAttribute(„class‟,‟errorname‟);
    16. 16. Creating New Nodes Create element nodes by createElement() and createTextNode(). Once you have the new nodes, you add them to the DOM tree with appendChild(). Example  var myp = document.createElement(p);  myp.innerHTML = yet another;  = 2px dotted blue’  document.body.appendChild(myp) //here appended to end of body directly
    17. 17. Clone Existing Node cloneNode()  The method accepts a boolean parameter (true = deep copy with all the children, false = shallow copy, only this node).  Get a reference to the element you want to clone:  var el = document.getElementsByTagName(p)[1];  Create a shallow clone of el and append it to the body:  document.body.appendChild(el.cloneNode(false))  Create a deep copy, the whole DOM subtree  document.body.appendChild(el.cloneNode(true))
    18. 18. insertBefore insertBefore is the same as appendChild(), but accepts an extra parameter, specifying before which element to insert the new node. Example:  At the end of the body:  document.body.appendChild(document.createTextNode(boo!));  Add it as the first child of the body:  document.body.insertBefore(document.createTextNode(boo!), document.body.firstChild);
    19. 19. Removing/Replacing Nodes removeChild().  Specify node to be removed, send it to removeChild  var removed = document.body.removeChild(myp);  The method returns the removed node if you want to use it later. replaceChild()  Removes a node and puts another one in its place.  First specify node to remove and node to add, then send them to function  var replaced = document.body.replaceChild(removed, pAdded);  It returns a reference to the node that is now out of the tree.
    20. 20. Question? How to remove all subtree of body? document.body.innerHTML = ’’;
    21. 21. Events Events can be attached to JavaScript code through one of the following ways:  Inline HTML Attributes (already discussed)  Element Properties  DOM Event Listeners
    22. 22. Elements Properties assign a function to the on-event property of a DOM node element. Example: <div id="my-div">click</div> <script type="text/javascript"> var myelement = document.getElementById(my-div); myelement.onclick = function() { alert(Div Clicked!); } </script> You can attach only one function to the event.
    23. 23. DOM Event Listeners This method allows for many functions listening to an event. When the event fires, all functions are executed. Example: <p id="closer">final</p> var mypara = document.getElementById(my-div); mypara.addEventListener(click, function(){alert(Boo!’)}, false); mypara.addEventListener(click, myHandler, false); Where myHandler is a name of a defined function You can use anonymous functions such as function(){alert(Boo!)} or existing functions such as myHandler.
    24. 24. DOM Event Listeners As events are added using listeners they can be removed too. removeEventListener()  accepts exactly the same parameters. mypara.removeEventListener(click, myHandler, false); You cannot remove listeners that use anonymous functions. If you remove a listener, you have to pass a pointer to the same function you previously attached.
    25. 25. Always keep in mind thatHTML is for content, JavaScriptfor behavior and CSS forformatting, and you should keepthese three SEPARATE asmuch as possible.
    26. 26. HTML-only DOM objects document objects that represent a number of collections:  document.images  document.anchors  document.forms  document.links  document.styleSheets Other useful properties  document.cookie  document.referrer
    27. 27. document.images A collection of all images images on the page Equivalent to document.getElementsByTagName(„img)
    28. 28. Image Objects Image Object represent an HTML Image Has its own set of Properties, Collections, Methods & Event handlers. Properties:  name  id  src  height  width Image Preloading can boost performance, by creating Image objects and after loading start assigning them to HTML
    29. 29. document.anchors document.anchors- contains all links with a name attribute (<a name="..."></a>). Anchor Object  The Anchor object represents an HTMLAnchor.  Properties:  href  name  target
    30. 30. document.forms Form Object document.forms - contains a list of <form> tags. Properties of Form Object  elements[]: a collection of elements of the form  Example:  <input name="search" id="search" type="text” value="Enter email..." />  To change the text in the field by:  document.forms[0].elements[0].value =’  To disable the field dynamically:  document.forms[0].elements[0].disabled = true;  method,action
    31. 31. document.forms When forms or form elements have a name attribute, you can access them by name too:  document.forms[0].elements[search]; // array notation  document.forms[0]; // object property Methods of Form Object:  reset()  submit() Events of Form Object:  Onreset  onsubmit
    32. 32. Form Elements Events Use „this‟ keyword to refer to the current object. Self reference to the object is used  document.forms[0].elements[name].onchange=function(){al ert(this)} on text change will alert
    33. 33. Form Elements Common Properties  Common Methods  name  focus()/blur()  value  Common Events  form  onfocus/onblur  disabled  onclick/ondblclick  onmousedown  onmousemove/onmouseo ve  onmouseout/onmouseup
    34. 34. Input Text/Password Properties:  maxLength  readOnly Methods  select() Events  onchange
    35. 35. Input Radio/Checkbox Properties:  length  checked  defaultChecked Events  onclick  onchange
    36. 36. Input Button Events:  onclick  ondblclick  onmousedown  onmouseout  onmouseover  onmouseup
    37. 37. Select Properties  Method (not with IE  length prior 8 )  multiple  add()  selectedIndex  remove()  options[]  Events  selected  onchange  text  defaultSelected
    38. 38. Option Properties  selected  text  defaultSelected Options can be added dynamically to a Select element.  First create a new Option object.  Set its value and text.  Send to add method of Select Element.
    39. 39. Textarea Properties  Method:  cols  select()  defaultValue  Events  readOnly  onselect  rows
    40. 40. Try Form validation
    41. 41. styleSheets document.styleSheets[]  All the external style sheets on the page, either defined using the <style> or <link rel="stylesheet"> tag.  To add or delete rules within any stylesheet on the page.
    42. 42. styleSheets Properties cssRules[]  Returns an array containing all the CSS rules of a stylesheet. NS6+/Firefox only object. In IE (Win), use rules[] instead.  cssText  Read/write property that contains the entire contents of the stylesheet. IE only property. Note that Firefox support a "cssText" property on individual rules to return the contents of each rule. disabled :  Read/write property that specifies whether a stylesheet is diabled or not. Default value is false. href  Read/write property that specifies the URL of an external stylesheet. media  Specifies the medium of the stylesheet. Default value is "screen.”
    43. 43. styleSheets[] Methods addRule(selector, declaration, [index])  IE : adds a new rule to the stylesheet,  "selector” ex: "p", "div b” ……etc  "declaration” ex: "background-color: yellow; color: brown”  "index" optional, default is -1, which adds the new rule to the end. removeRule([index]) :  IE: removes the first rule, index (optional) to remove rule at index. deleteRule(index):  Removes a rule based on its index. DOM2 NS/Firefox only property. insertRule(rule, index):  Inserts a new rule to the stylesheet,  "rule” ex: #myid{color: red; border: 1px solid black}  "index", NS/Firefox only property.
    44. 44. document.cookie It is a property that contains a string, the content of the cookies exchanged between the server and the client. When the server sends a page to the browser, it may include the Set-Cookie HTTP header. When the client sends a request to the server, it sends the cookie information back with the Cookie header.
    45. 45. document.cookie Cookie Attributes  name-value pair  Each cookie has a name-value pair that contains the actual information.  expires  If not specified, the cookie is trashed when you close the browser. It id in UTC (Greenwich) time.  path  to specify directory where the cookie is active. Usually „/‟,  the entire domain.  domain  Which domain the cookie should be sent to. Other domains cannot read them.  Can‟t be set to a domain other than the one setting it.
    46. 46. document.cookie To set cookie, assign string with all attributes to document.cookie Example:  var nextyear = new Date( ); nextyear.setFullYear(nextyear.getFullYear( ) + 1);  document.cookie = ”intake=33;track=PD; expires=" + nextyear.toGMTString( );
    47. 47. How to DELETE a cookie Create a cookie with expired date
    48. 48. document.referrer Returns the URI of the page that linked to this page. This is the same value the browser sends in the Referer HTTP header when requesting the page. There is also:  document.location  document.title  document.domain
    49. 49. References DomScripting, Web Design with JavaScript and DOM, Jeremy Keith, 2008 . Object-Oriented JavaScript Create Scalable, reusable, high quality JavaScript applications and libraries, Stoyan Stefanov, 2008. JavaScript by Example, Second Edition, Ellie Quigley, 2011 JavaScript, the Definitive Guide, 5th edition, David Flanagan, 2006