DOM Scripting
- Use underscore for variable name and camel case for function:
var temp_celsius; function convertToCelsius(){}
- Use var to define a local variable, if not defined with var, the variable will be treated as global.
- 3 kinds of objects in javascript: Native; User-defined; Host(browser provided).
- Native objects:
var current_date = new Date(); current_date.getDate(); // getHours(); getMonth();
- Objects that are supplied by the web browser are called host objects. An important object: document.
- When you load your document into the browser, the DOM comes to life and the document turns into an object.
- window object is a global object, and document is a property of window object(window.document).
- If the document is a tree(node tree), then the <html> element will be the root.
- wildcard: alert(getElementsByTagName("*").length); // will give you the total number of element nodes in a document.
- getElementById("purchases").getElementsByTagName("*");
- getElementsByClassName(class): will return an array, the order of the class name doesn't matter, matches if the element has addtional classes.
- scripters' getElementByClassName function:(work only for single class)
1 function getElementsByClassName(node, classname){ 2 if(node.getElementsByClassName){ 3 // use the existing method 4 return node.getElementByClassName(classname); 5 } else { 6 var res = new Array(); 7 var elems = node.getElementsByTagName("*"); 8 for(var i = 0; i < elems.length; i++){ 9 if(elems[i].className.indexOf(classname) != -1){ 10 res[res[i]] = elems[i]; 11 } 12 } 13 return res; 14 } 15 }
- every element node in a document is an object.
- getAttribute("title") will return null if there is no such attribute.
- if(something) is a shorthand way of if(something != null)
- childNodes: it returns an array containing all the children of an element node(with attribute nodes, text nodes as well).
- nodeType:(node.nodeType)
- Element nodes have nodeType value of 1;
- Attribute nodes have nodeType value of 2;
- Text nodes have nodeType value of 3.
- nodeValue(can be used to retrieve or set value):
var description = document.getElementById("description"); // <p id="description">Choose an image</p> var text = description.childNodes[0].nodeValue; // get the text node value
// the paragraph's nodeValue itself is empty. - firstChild, lastChild:
// node.firstChild is equivalent to node.childNodes[0] // node.lastChild = node.childNodes[node.childNodes.length - 1]
- A simple popup window:
// syntax: window.open(url, name, features); // such as: function popUp(Url){ window.open(Url, "popUp", "width=320,height=480"); }
- <a href="#">Bla bla bla</a>: The '#' symbol is used for internal links within document.(in this case, it's an internal link to nowhere)
- 'this' can be used to refer to the current element:
<a href="http://www.google.com" onclick="popUp(this.href);return false;"></a> // an example of graceful degradation
- .href property:
// <a id="link" href="http://www.google.com"></a> document.write(document.getElementById("link").href);
// syntax: elementObject.href - the document object is a property of the window object
window.onload = preparelins;
function preparelinks(){
var links = document.getElementsByTagName("a"); for(var i = 0; i < links.length; i++){ if(links[i].getAttribute("class") == "popup"){ links[i].onclick = function(){ popUp(this.getAttribute("href")); return false; } } }
}
function popUp(Url){window.open(Url, "popup", "width=320,height=480;")} - Object detection:
function myFunc(){ if(document.getElementById){ // statements; } }
- Better test for getElementById:
if(!getElementById){ return false; }
// equals:
if(!getElementById)return false; - Wrap everthing up:
window.onload = function(){ if(!document.getElementsByTagName) return false; var links = document.getElementsByTagName("a"); for(var i = 0; i < links.length; i++){ if(links[i].getAttribute("class") == "popup"){ link[i].onclick = function(){ popUp(this.getAttribute("a")); return false; } } } }
- Performance considerations:
- Minimizing DOM access and markup
- Assembling and placing scripts
- Minification(Minification refers to the process of taking your script and “compressing” it by removing the unnecessary bits such as whitespace and comments); better keep two files at hand, one for working, another for minimized file(use min in your file name)
- Available minification tools:
1 Douglas Crockford’s JSMin (http://www.crockford.com/javascript/jsmin.html) 2 Yahoo!’s YUI Compressor (http://developer.yahoo.com/yui/compressor/) 3 Google’s Closure Compiler (http://closure-compiler.appspot.com/home)
- createElement:
window.onload = function(){ var testdiv = document.getElementById("testdiv"), para = document.createElement("p"), info = "nodeName: "; info += para.nodeName; info += " nodeType: "; info += para.nodeType; alert(info); }// whenever you create an element, it's called a document fragment. It has nodeName, nodeType value.
- appendChild:
testdiv.appendChild(para);
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
- insertBefore: syntax, parentElement.insertBefore(newElement, targetElement);
var gallery = document.getElementById("imagegallery"); gallery.parentNode.insertBefore(placeholder, gallery);
DOM does not have a insert-after method, we can create one:
function insertAfter(newElement, targetElement){ var parent = targetElement.parentNode; if(targetElement == parent.lastChild){ parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } }
- addLoadEvent function:
function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload != 'function'){ windwo.onload = func; } else { window.onload = function(){ oldonload(); func(); } } }
- DOM-core and HTML-DOM:
// DOM-core: document.getElementsByTagName("body")[0]; // HTML-DOM: document.body;
- Internet Explorer will count up the child nodes for each <abbr> element and incorrectly come up with zero each time. So, for compatibility issues, you wanna add these lines to deal with <abbr> elements:
var abbreviations = document.getElementsByTagName("abbr"); // inside for loop: if(abbreviations[i].childNodes.length<1) continue;
- Notice:
<blockquote> <p> Some sentences... </p> </blockquote>
between the end of </p> element and the </blockquote> element, there is a line break, some browers will treat this line break as a text node. That means the lastChild property of blockquote element node isn't p element node, it's a text node. When in doubt, you can use nodeType to check it out.
- wildcard character:
var quoteElements = document.getElementsByTagName("*"); // returns an array of elements regardless of name
- Access key: The accesskey attribute associates an element, such as a link, with a specific key on a keyboard. On many Windows browsers, you can press Alt+access key; on many Mac browsers, you can press Ctrl+access key.
<a href="index.html" accesskey="1">Home</a> // see http://clagnut.com/blog/193/
// var links = document.getElementsByTagName("a"); links[0].firstChild.nodeValue; // 'Home'// links[0].firstChild.nodeValue; // 'Home' - every element object has a style property, and it is returned as an object. Style information is stored as properties of this style object:
element.style.property
when retrieve font-family info, you should:
element.style.fontFamily; // not element.style.font-family // it will treat - as substraction
The camel-casing convention applies to just about any CSS property that contains one or more dashes. Such as, background-color:backgroundColor; font-weight: fontWeight; magrin-top-width:marginTopWidth; The style object only work for inline style, not for external or <style> block in the <head> section.
- The value of a style property is always a string:
var para = document.getElementById("example"); para.style.color = black; // wrong para.style.color = "black"; // right
- Using tables for layout is not a good idea, But you should definitely use tables to display tabular data.
- className: an earily version to get access to class attribute:
element.className = value; // to avoid overwriting the existed class value, you can use:
element.className += value; - The process of take something very specific and turning it into something more general is called abstraction. Usually for code reuse.
- setTimeout: takes 2 arguments, first one is the function name, second is the millisecond before executing the function:
variable = setTimeout("function", interval);
clearTimeout(variable); // cancel a pending action
var num = parseInt(string); // extract number from a string
var steps = parseInt("39 stepts"); // return 39
var num2 = parseFloat(string); - Modernizr: a small library for HTML5 feature detection. Download it(http://www.modernizr.com) and add a script to the <head> of your document:
<script src="modernizr-1.5.min.js"></script>
- To reduce the number of requests, put all your code into a global.js file. Also, use basic.css and do:
@import url(color.css); @import url(layout.css); // ...
- Several usefull functions:
function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload != 'function'){ window.onload = func; } else { window.onload = function(){ oldonload(); func(); } } } function addClass(element, value){ if(!element.className){ element.className = value; } else { newClassName = element.className; newClassName += " "; newClassName += value; element.className = newClassName; } }
- You can get the URL of the current page using window.location.href;
- what labels used for:
// in case there is no browser support for label focus function focusLabels(){ if(!document.getElementsByTagName) return false; var labels = document.getElementsByTagName("label"); for (var i = 0; i < labels.length; i++){ if(!labels[i].getAttribute("for")) continue; labels[i].onclick = function(){ var id = this.getAttribute("for"); if(!document.getElementById(id)) return false; var element = document.getElementById(id); element.focus(); } } }
- form.elements.length: returns the number of elements contained by a form, The elements.length property of a Form object returns only those elements that are form elements, such as input elements, textarea elements, and so on.
- form.elements is an array contains all the form elements.
- hasChildNodes() method: returns a Boolean value indicating whether the current Node has child nodes or not.
- elementNode.removeChild(node): remove a child node;
- The encodeURIcomponent() function encodes a URI component:
var uri="http://w3schools.com/my test.asp?name=ståle&car=saab"; document.write(encodeURIComponent(uri));
- Google's Closure Compiler for minification:http://closure-compiler.appspot.com/home
- CDN: Content Delivery Network solves the problems of shared library distribution. Include the URL in the <script> src attribute.
- n
- n
- n