Upgrade to ExtJS 3.2.1 - Released 04/27/2010
[extjs.git] / docs / source / DomHelper.html
1 <html>
2 <head>
3   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
4   <title>The source code</title>
5     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
6     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 </head>
8 <body  onload="prettyPrint();">
9     <pre class="prettyprint lang-js">/*!
10  * Ext JS Library 3.2.1
11  * Copyright(c) 2006-2010 Ext JS, Inc.
12  * licensing@extjs.com
13  * http://www.extjs.com/license
14  */
15 <div id="cls-Ext.DomHelper"></div>/**
16  * @class Ext.DomHelper
17  * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
18  * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
19  * from your DOM building code.</p>
20  *
21  * <p><b><u>DomHelper element specification object</u></b></p>
22  * <p>A specification object is used when creating elements. Attributes of this object
23  * are assumed to be element attributes, except for 4 special attributes:
24  * <div class="mdetail-params"><ul>
25  * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
26  * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
27  * same kind of element definition objects to be created and appended. These can be nested
28  * as deep as you want.</div></li>
29  * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
30  * This will end up being either the "class" attribute on a HTML fragment or className
31  * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
32  * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
33  * </ul></div></p>
34  *
35  * <p><b><u>Insertion methods</u></b></p>
36  * <p>Commonly used insertion methods:
37  * <div class="mdetail-params"><ul>
38  * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
39  * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
40  * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
41  * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
42  * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
43  * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
44  * </ul></div></p>
45  *
46  * <p><b><u>Example</u></b></p>
47  * <p>This is an example, where an unordered list with 3 children items is appended to an existing
48  * element with id <tt>'my-div'</tt>:<br>
49  <pre><code>
50 var dh = Ext.DomHelper; // create shorthand alias
51 // specification object
52 var spec = {
53     id: 'my-ul',
54     tag: 'ul',
55     cls: 'my-list',
56     // append children after creating
57     children: [     // may also specify 'cn' instead of 'children'
58         {tag: 'li', id: 'item0', html: 'List Item 0'},
59         {tag: 'li', id: 'item1', html: 'List Item 1'},
60         {tag: 'li', id: 'item2', html: 'List Item 2'}
61     ]
62 };
63 var list = dh.append(
64     'my-div', // the context element 'my-div' can either be the id or the actual node
65     spec      // the specification object
66 );
67  </code></pre></p>
68  * <p>Element creation specification parameters in this class may also be passed as an Array of
69  * specification objects. This can be used to insert multiple sibling nodes into an existing
70  * container very efficiently. For example, to add more list items to the example above:<pre><code>
71 dh.append('my-ul', [
72     {tag: 'li', id: 'item3', html: 'List Item 3'},
73     {tag: 'li', id: 'item4', html: 'List Item 4'}
74 ]);
75  * </code></pre></p>
76  *
77  * <p><b><u>Templating</u></b></p>
78  * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
79  * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
80  * insert new elements. Revisiting the example above, we could utilize templating this time:
81  * <pre><code>
82 // create the node
83 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
84 // get template
85 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
86
87 for(var i = 0; i < 5, i++){
88     tpl.append(list, [i]); // use template to append to the actual node
89 }
90  * </code></pre></p>
91  * <p>An example using a template:<pre><code>
92 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
93
94 var tpl = new Ext.DomHelper.createTemplate(html);
95 tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack&#39;s Site"]);
96 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
97  * </code></pre></p>
98  *
99  * <p>The same example using named parameters:<pre><code>
100 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
101
102 var tpl = new Ext.DomHelper.createTemplate(html);
103 tpl.append('blog-roll', {
104     id: 'link1',
105     url: 'http://www.jackslocum.com/',
106     text: "Jack&#39;s Site"
107 });
108 tpl.append('blog-roll', {
109     id: 'link2',
110     url: 'http://www.dustindiaz.com/',
111     text: "Dustin&#39;s Site"
112 });
113  * </code></pre></p>
114  *
115  * <p><b><u>Compiling Templates</u></b></p>
116  * <p>Templates are applied using regular expressions. The performance is great, but if
117  * you are adding a bunch of DOM elements using the same template, you can increase
118  * performance even further by {@link Ext.Template#compile "compiling"} the template.
119  * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
120  * broken up at the different variable points and a dynamic function is created and eval'ed.
121  * The generated function performs string concatenation of these parts and the passed
122  * variables instead of using regular expressions.
123  * <pre><code>
124 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
125
126 var tpl = new Ext.DomHelper.createTemplate(html);
127 tpl.compile();
128
129 //... use template like normal
130  * </code></pre></p>
131  *
132  * <p><b><u>Performance Boost</u></b></p>
133  * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
134  * of DOM can significantly boost performance.</p>
135  * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
136  * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
137  * results in the creation of a text node. Usage:</p>
138  * <pre><code>
139 Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
140  * </code></pre>
141  * @singleton
142  */
143 Ext.DomHelper = function(){
144     var tempTableEl = null,
145         emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
146         tableRe = /^table|tbody|tr|td$/i,
147         confRe = /tag|children|cn|html$/i,
148         tableElRe = /td|tr|tbody/i,
149         cssRe = /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
150         endRe = /end/i,
151         pub,
152         // kill repeat to save bytes
153         afterbegin = 'afterbegin',
154         afterend = 'afterend',
155         beforebegin = 'beforebegin',
156         beforeend = 'beforeend',
157         ts = '<table>',
158         te = '</table>',
159         tbs = ts+'<tbody>',
160         tbe = '</tbody>'+te,
161         trs = tbs + '<tr>',
162         tre = '</tr>'+tbe;
163
164     // private
165     function doInsert(el, o, returnElement, pos, sibling, append){
166         var newNode = pub.insertHtml(pos, Ext.getDom(el), createHtml(o));
167         return returnElement ? Ext.get(newNode, true) : newNode;
168     }
169
170     // build as innerHTML where available
171     function createHtml(o){
172         var b = '',
173             attr,
174             val,
175             key,
176             keyVal,
177             cn;
178
179         if(typeof o == "string"){
180             b = o;
181         } else if (Ext.isArray(o)) {
182             for (var i=0; i < o.length; i++) {
183                 if(o[i]) {
184                     b += createHtml(o[i]);
185                 }
186             };
187         } else {
188             b += '<' + (o.tag = o.tag || 'div');
189             for (attr in o) {
190                 val = o[attr];
191                 if(!confRe.test(attr)){
192                     if (typeof val == "object") {
193                         b += ' ' + attr + '="';
194                         for (key in val) {
195                             b += key + ':' + val[key] + ';';
196                         };
197                         b += '"';
198                     }else{
199                         b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
200                     }
201                 }
202             };
203             // Now either just close the tag or try to add children and close the tag.
204             if (emptyTags.test(o.tag)) {
205                 b += '/>';
206             } else {
207                 b += '>';
208                 if ((cn = o.children || o.cn)) {
209                     b += createHtml(cn);
210                 } else if(o.html){
211                     b += o.html;
212                 }
213                 b += '</' + o.tag + '>';
214             }
215         }
216         return b;
217     }
218
219     function ieTable(depth, s, h, e){
220         tempTableEl.innerHTML = [s, h, e].join('');
221         var i = -1,
222             el = tempTableEl,
223             ns;
224         while(++i < depth){
225             el = el.firstChild;
226         }
227 //      If the result is multiple siblings, then encapsulate them into one fragment.
228         if(ns = el.nextSibling){
229             var df = document.createDocumentFragment();
230             while(el){
231                 ns = el.nextSibling;
232                 df.appendChild(el);
233                 el = ns;
234             }
235             el = df;
236         }
237         return el;
238     }
239
240     /**
241      * @ignore
242      * Nasty code for IE's broken table implementation
243      */
244     function insertIntoTable(tag, where, el, html) {
245         var node,
246             before;
247
248         tempTableEl = tempTableEl || document.createElement('div');
249
250         if(tag == 'td' && (where == afterbegin || where == beforeend) ||
251            !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
252             return;
253         }
254         before = where == beforebegin ? el :
255                  where == afterend ? el.nextSibling :
256                  where == afterbegin ? el.firstChild : null;
257
258         if (where == beforebegin || where == afterend) {
259             el = el.parentNode;
260         }
261
262         if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
263             node = ieTable(4, trs, html, tre);
264         } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
265                    (tag == 'tr' && (where == beforebegin || where == afterend))) {
266             node = ieTable(3, tbs, html, tbe);
267         } else {
268             node = ieTable(2, ts, html, te);
269         }
270         el.insertBefore(node, before);
271         return node;
272     }
273
274
275     pub = {
276         <div id="method-Ext.DomHelper-markup"></div>/**
277          * Returns the markup for the passed Element(s) config.
278          * @param {Object} o The DOM object spec (and children)
279          * @return {String}
280          */
281         markup : function(o){
282             return createHtml(o);
283         },
284
285         <div id="method-Ext.DomHelper-applyStyles"></div>/**
286          * Applies a style specification to an element.
287          * @param {String/HTMLElement} el The element to apply styles to
288          * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
289          * a function which returns such a specification.
290          */
291         applyStyles : function(el, styles){
292             if(styles){
293                 var i = 0,
294                     len,
295                     style,
296                     matches;
297
298                 el = Ext.fly(el);
299                 if(typeof styles == "function"){
300                     styles = styles.call();
301                 }
302                 if(typeof styles == "string"){
303                     while((matches = cssRe.exec(styles))){
304                         el.setStyle(matches[1], matches[2]);
305                     }
306                 }else if (typeof styles == "object"){
307                     el.setStyle(styles);
308                 }
309             }
310         },
311
312         <div id="method-Ext.DomHelper-insertHtml"></div>/**
313          * Inserts an HTML fragment into the DOM.
314          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
315          * @param {HTMLElement} el The context element
316          * @param {String} html The HTML fragment
317          * @return {HTMLElement} The new node
318          */
319         insertHtml : function(where, el, html){
320             var hash = {},
321                 hashVal,
322                 setStart,
323                 range,
324                 frag,
325                 rangeEl,
326                 rs;
327
328             where = where.toLowerCase();
329             // add these here because they are used in both branches of the condition.
330             hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
331             hash[afterend] = ['AfterEnd', 'nextSibling'];
332
333             if (el.insertAdjacentHTML) {
334                 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
335                     return rs;
336                 }
337                 // add these two to the hash.
338                 hash[afterbegin] = ['AfterBegin', 'firstChild'];
339                 hash[beforeend] = ['BeforeEnd', 'lastChild'];
340                 if ((hashVal = hash[where])) {
341                     el.insertAdjacentHTML(hashVal[0], html);
342                     return el[hashVal[1]];
343                 }
344             } else {
345                 range = el.ownerDocument.createRange();
346                 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
347                 if (hash[where]) {
348                     range[setStart](el);
349                     frag = range.createContextualFragment(html);
350                     el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
351                     return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
352                 } else {
353                     rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
354                     if (el.firstChild) {
355                         range[setStart](el[rangeEl]);
356                         frag = range.createContextualFragment(html);
357                         if(where == afterbegin){
358                             el.insertBefore(frag, el.firstChild);
359                         }else{
360                             el.appendChild(frag);
361                         }
362                     } else {
363                         el.innerHTML = html;
364                     }
365                     return el[rangeEl];
366                 }
367             }
368             throw 'Illegal insertion point -> "' + where + '"';
369         },
370
371         <div id="method-Ext.DomHelper-insertBefore"></div>/**
372          * Creates new DOM element(s) and inserts them before el.
373          * @param {Mixed} el The context element
374          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
375          * @param {Boolean} returnElement (optional) true to return a Ext.Element
376          * @return {HTMLElement/Ext.Element} The new node
377          */
378         insertBefore : function(el, o, returnElement){
379             return doInsert(el, o, returnElement, beforebegin);
380         },
381
382         <div id="method-Ext.DomHelper-insertAfter"></div>/**
383          * Creates new DOM element(s) and inserts them after el.
384          * @param {Mixed} el The context element
385          * @param {Object} o The DOM object spec (and children)
386          * @param {Boolean} returnElement (optional) true to return a Ext.Element
387          * @return {HTMLElement/Ext.Element} The new node
388          */
389         insertAfter : function(el, o, returnElement){
390             return doInsert(el, o, returnElement, afterend, 'nextSibling');
391         },
392
393         <div id="method-Ext.DomHelper-insertFirst"></div>/**
394          * Creates new DOM element(s) and inserts them as the first child of el.
395          * @param {Mixed} el The context element
396          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
397          * @param {Boolean} returnElement (optional) true to return a Ext.Element
398          * @return {HTMLElement/Ext.Element} The new node
399          */
400         insertFirst : function(el, o, returnElement){
401             return doInsert(el, o, returnElement, afterbegin, 'firstChild');
402         },
403
404         <div id="method-Ext.DomHelper-append"></div>/**
405          * Creates new DOM element(s) and appends them to el.
406          * @param {Mixed} el The context element
407          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
408          * @param {Boolean} returnElement (optional) true to return a Ext.Element
409          * @return {HTMLElement/Ext.Element} The new node
410          */
411         append : function(el, o, returnElement){
412             return doInsert(el, o, returnElement, beforeend, '', true);
413         },
414
415         <div id="method-Ext.DomHelper-overwrite"></div>/**
416          * Creates new DOM element(s) and overwrites the contents of el with them.
417          * @param {Mixed} el The context element
418          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
419          * @param {Boolean} returnElement (optional) true to return a Ext.Element
420          * @return {HTMLElement/Ext.Element} The new node
421          */
422         overwrite : function(el, o, returnElement){
423             el = Ext.getDom(el);
424             el.innerHTML = createHtml(o);
425             return returnElement ? Ext.get(el.firstChild) : el.firstChild;
426         },
427
428         createHtml : createHtml
429     };
430     return pub;
431 }();
432 </pre>    
433 </body>
434 </html>