dom api in java script
DESCRIPTION
TRANSCRIPT
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
DOM API in JavaScript
3Thursday, September 24, 2009
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
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
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
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
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
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
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
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
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
Mouse EventsThe target is the topmost (z-index) node containing the cursor
clickdblclickmousedownmousemovemouseoutmouseovermouseup
13Thursday, September 24, 2009
Input EventsThe target is the node having focus
blurchangefocuskeydownkeypresskeyupresetsubmit
14Thursday, September 24, 2009
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
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
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
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
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
Cancel BubblingCancel bubbling to keep the parent nodes from seeing the event
e.cancelBubble = true; // IEif (e.stopPropogation) {
e.stopPropogation();}
19Thursday, September 24, 2009
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
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
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
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
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
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
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
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
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
CopingDo what worksDo what is commonDo what is standard (sad this is not #1)
29Thursday, September 24, 2009
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
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
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