dom api in java script

33
JavaScript DOM API Rajat Pandit ([email protected] ) 1 Thursday, September 24, 2009

Upload: rajat-pandit

Post on 31-Oct-2014

4.002 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Dom API In Java Script

JavaScript DOM API

Rajat Pandit ([email protected])

1Thursday, September 24, 2009

Page 2: Dom API In Java Script

Document Object ModelW3C thought it was a good idea to keep the DOM API similar across languagesVague specifications meant different implementations across different browsersIt became important to know the difference between browsers to make code work across different browsersThat didn’t turn out as expected

2Thursday, September 24, 2009

Page 3: Dom API In Java Script

DOM API in JavaScript

3Thursday, September 24, 2009

Page 4: Dom API In Java Script

Finding ElementsDOM API provides for the following methods

document.getElementById(id) - Gets element by its id

document.getElementsByTagName(tagname) - Get all the elements matching tagname

document.getElementsByClassName(class) - Currently only support by Firefox :(

4Thursday, September 24, 2009

Page 5: Dom API In Java Script

Modifying ElementsOld School Method (smaller & faster)

W3C way of changing attributes.

if (my_image.complete) {my_image.src = support_url;

}

if (my_image.getAttribute('complete')) { my_image.setAttribute('src',url);}

5Thursday, September 24, 2009

Page 6: Dom API In Java Script

Changing style of elementsnode.classNamenode.style.stylenamenode.currentStyle.stylename

Only supported by IE so far, reports back the computed style, similar to firebug

6Thursday, September 24, 2009

Page 7: Dom API In Java Script

Style Names (css/js)css style name javascript

equivalentbackground-color backgroundColorborder-radius borderRadius

font-size fontSizelist-style-type listStyleTypeword-spacing wordSpacing

z-index zIndex

7Thursday, September 24, 2009

Page 8: Dom API In Java Script

Making New ElementsDOM allows you to create new elementsdocument.createElement(nodename) - creates a new node elementdocument.createTextNode(text) - creates the node of type #textnode.cloneNode(boolean) - clones the node and creates a new instance, when set to true, clones all its decendents a well.Important thing to remember is, the new nodes are not attached to the DOM

8Thursday, September 24, 2009

Page 9: Dom API In Java Script

Linking Elements to a parentnode.appendChild(new_node) - attaches new_node to node as a descendentnode.insertBefore(new_node, sibling) - adds new_node before the sibling node (pretty odd)node.replaceChild(new, old) - replaces old node with the new nodebetter written as old.parentNode.replaceChild(new, old)Very odd that all methods require link to the parent node

9Thursday, September 24, 2009

Page 10: Dom API In Java Script

Removing NodesRemoving nodes is even weirdernode.removeChild(old) - how odd!!better written as old.parentNode.removeChild(old) I call it the suicide method

10Thursday, September 24, 2009

Page 11: Dom API In Java Script

innerHTMLNot part of the original W3C spec

added by IE and now all a-grade browsers support it

You can do the same by appendChild but it can be really complex for bigger structures

Which option is better? readability and clean code should always take a higher priority when taking that decision

11Thursday, September 24, 2009

Page 12: Dom API In Java Script

Event ModelThe browser has an event driven single treaded, asynchronous programming modelEvents are targeted at particular nodesEvents cause the invocation of event handlers

12Thursday, September 24, 2009

Page 13: Dom API In Java Script

Mouse EventsThe target is the topmost (z-index) node containing the cursor

clickdblclickmousedownmousemovemouseoutmouseovermouseup

13Thursday, September 24, 2009

Page 14: Dom API In Java Script

Input EventsThe target is the node having focus

blurchangefocuskeydownkeypresskeyupresetsubmit

14Thursday, September 24, 2009

Page 15: Dom API In Java Script

Attaching Event HandlersClassic Method (still works)

W3C Way

MS Way (Why not!!)

node[“on” + type] = f

node.addEventListener(type, f, false)

node.attachEvent(“on”+type, f)

15Thursday, September 24, 2009

Page 16: Dom API In Java Script

Event HandlersThe handler takes an optional event parameter

MS doesn’t send an event param to the handler, use the global event object instead. Screws up meaning of “this” object

function(e) {e = e || event;var target =

e.target || e.srcElement;// more code.

}

16Thursday, September 24, 2009

Page 17: Dom API In Java Script

Event DispatchingTrickling - is an event capturing pattern which provides compatibility with NS4. Track event at the top and work the way down till it finds the node. Crazy Idea, avoid it!!

Bubbling - Event is given to an element and passes on to its parent and then its parent or so until it’s cancelled.

17Thursday, September 24, 2009

Page 18: Dom API In Java Script

Event DispatchingTrickling - is an event capturing pattern which provides compatibility with NS4. Track event at the top and work the way down till it finds the node. Crazy Idea, avoid it!!

Bubbling - Event is given to an element and passes on to its parent and then its parent or so until it’s cancelled.

MS got this one right

17Thursday, September 24, 2009

Page 19: Dom API In Java Script

Why Bubble?Assume a case of 100 draggable objectsAttach 100 event handlers,one to each objector attach 1 Event handler to the container and find out the target from there instead

18Thursday, September 24, 2009

Page 20: Dom API In Java Script

Cancel BubblingCancel bubbling to keep the parent nodes from seeing the event

e.cancelBubble = true; // IEif (e.stopPropogation) {

e.stopPropogation();}

19Thursday, September 24, 2009

Page 21: Dom API In Java Script

Prevent Default ActionAn event handler can prevent browser action associated with the event (such as submitting the form)

e.returnValue = false;if (e.preventDefault) {

e.preventDefault();}return false;

20Thursday, September 24, 2009

Page 22: Dom API In Java Script

Memory ManagementUsually gc algo on most browsers is pretty goodAlways a good idea to set null to a variable when no longer is usedIE 6 Memory leak issue (make sure you remove event handlers before removing an element)IE6 uses reference counting garbage collector algo (+1 for reference, -1 when set to null when zero its garbaged collected)reference counting is not able to reclaim cyclic structurethese cycles need to be broken manually

21Thursday, September 24, 2009

Page 23: Dom API In Java Script

Memory Leaks on IE6Not an issue for page view driven applicationsbut a show stopper for AJAX ApplicationsNow fixed in IE7Remove all event handlers from elements due to be deletedMust be done for nodes before removeChild / replaceChildIt must be done on nodes before they are replaced by innerHTML

22Thursday, September 24, 2009

Page 24: Dom API In Java Script

Memory Leaks in IE6You can use YUI’s purgeElement method or

function purgeEventHandlers(node) {for(var n in node) {if (typeof node[n] === ‘function’) {node[n] = null;

}}

}

23Thursday, September 24, 2009

Page 25: Dom API In Java Script

More JavaScript ElementsThese are assumed to be part of JavaScript but actually provided by DOM

alert(text)confirm(text)prompt(text, default_value)Don’t use these for AJAX apps as they break the async form, use YUI dialogues instead

setTimeout(func, msec)setInterval(func, msec)

24Thursday, September 24, 2009

Page 26: Dom API In Java Script

window objectThe window object is the javascript global objectIt’s the meeting point between JS/DOMEvery window, frame, iframe has its own window objectAKA self

25Thursday, September 24, 2009

Page 27: Dom API In Java Script

Inter-window communicationframe[] - child frames and iframesname - text name for the windowopener - reference to the opener of current window objectparent - reference to the parentself - reference to this windowtop - reference to the outermost windowwindow - reference to the current windowopen() - opens a new window

26Thursday, September 24, 2009

Page 28: Dom API In Java Script

More on inter-window communication

A script can access another window if it can get a reference to it

Same Origin PolicyWorkaround, if a.b.com needs to talk to c.b.com set

document.domain = otherwindow.document.domain

document.domain = c.b.com

27Thursday, September 24, 2009

Page 29: Dom API In Java Script

Cross Browser IssuesWeak standards result in significant vendor specific differences between the browsersThere are three ways of resolving it

Browser Detection - worked well when there were only a few browsers to supportFeature Detection - By far the safest way, check if the value exists before you use itPlatform Libraries - Use MS Atlas or Yahoo! YUI

28Thursday, September 24, 2009

Page 30: Dom API In Java Script

CopingDo what worksDo what is commonDo what is standard (sad this is not #1)

29Thursday, September 24, 2009

Page 31: Dom API In Java Script

The limiting FactorBrowsers are being pushed to their limitsBe prepared to back offReduce memory requirementsBalance client and server actions (don’t try and do everything on client side)

30Thursday, September 24, 2009

Page 32: Dom API In Java Script

What to watch out for?Browsers weren’t designed to be a general purpose application (newer versions are doing that, chrome is the right direction)Lacks a compositing model - new elements can’t be made with current elements, visually yes but browsers/screen readers still see them as individual elements

Lacks support for co-operation under mutual suspicion (mashups need to be written extra carefully to ensure there is no clobbering)

31Thursday, September 24, 2009

Page 33: Dom API In Java Script

ResourcesDOM Cheat Sheet By Christian

http://www.wait-till-i.com/2007/06/27/dom-javascript-cheat-sheet/

Mozilla’s take on DOMhttps://developer.mozilla.org/en/DOM

Convert Markup to DOM methodshttp://muffinresearch.co.uk/code/javascript/DOMTool/

32Thursday, September 24, 2009