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