Tweak the logic for fixing event.which. Fixes #2338.
[jquery.git] / src / manipulation.js
1 (function( jQuery ) {
2
3 var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
4         rleadingWhitespace = /^\s+/,
5         rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
6         rtagName = /<([\w:]+)/,
7         rtbody = /<tbody/i,
8         rhtml = /<|&#?\w+;/,
9         rnocache = /<(?:script|object|embed|option|style)/i,
10         rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,  // checked="checked" or checked (html5)
11         raction = /\=([^="'>\s]+\/)>/g,
12         wrapMap = {
13                 option: [ 1, "<select multiple='multiple'>", "</select>" ],
14                 legend: [ 1, "<fieldset>", "</fieldset>" ],
15                 thead: [ 1, "<table>", "</table>" ],
16                 tr: [ 2, "<table><tbody>", "</tbody></table>" ],
17                 td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
18                 col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
19                 area: [ 1, "<map>", "</map>" ],
20                 _default: [ 0, "", "" ]
21         };
22
23 wrapMap.optgroup = wrapMap.option;
24 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
25 wrapMap.th = wrapMap.td;
26
27 // IE can't serialize <link> and <script> tags normally
28 if ( !jQuery.support.htmlSerialize ) {
29         wrapMap._default = [ 1, "div<div>", "</div>" ];
30 }
31
32 jQuery.fn.extend({
33         text: function( text ) {
34                 if ( jQuery.isFunction(text) ) {
35                         return this.each(function(i) {
36                                 var self = jQuery(this);
37                                 self.text( text.call(this, i, self.text()) );
38                         });
39                 }
40
41                 if ( typeof text !== "object" && text !== undefined ) {
42                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
43                 }
44
45                 return jQuery.text( this );
46         },
47
48         wrapAll: function( html ) {
49                 if ( jQuery.isFunction( html ) ) {
50                         return this.each(function(i) {
51                                 jQuery(this).wrapAll( html.call(this, i) );
52                         });
53                 }
54
55                 if ( this[0] ) {
56                         // The elements to wrap the target around
57                         var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
58
59                         if ( this[0].parentNode ) {
60                                 wrap.insertBefore( this[0] );
61                         }
62
63                         wrap.map(function() {
64                                 var elem = this;
65
66                                 while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
67                                         elem = elem.firstChild;
68                                 }
69
70                                 return elem;
71                         }).append(this);
72                 }
73
74                 return this;
75         },
76
77         wrapInner: function( html ) {
78                 if ( jQuery.isFunction( html ) ) {
79                         return this.each(function(i) {
80                                 jQuery(this).wrapInner( html.call(this, i) );
81                         });
82                 }
83
84                 return this.each(function() {
85                         var self = jQuery( this ), contents = self.contents();
86
87                         if ( contents.length ) {
88                                 contents.wrapAll( html );
89
90                         } else {
91                                 self.append( html );
92                         }
93                 });
94         },
95
96         wrap: function( html ) {
97                 return this.each(function() {
98                         jQuery( this ).wrapAll( html );
99                 });
100         },
101
102         unwrap: function() {
103                 return this.parent().each(function() {
104                         if ( !jQuery.nodeName( this, "body" ) ) {
105                                 jQuery( this ).replaceWith( this.childNodes );
106                         }
107                 }).end();
108         },
109
110         append: function() {
111                 return this.domManip(arguments, true, function( elem ) {
112                         if ( this.nodeType === 1 ) {
113                                 this.appendChild( elem );
114                         }
115                 });
116         },
117
118         prepend: function() {
119                 return this.domManip(arguments, true, function( elem ) {
120                         if ( this.nodeType === 1 ) {
121                                 this.insertBefore( elem, this.firstChild );
122                         }
123                 });
124         },
125
126         before: function() {
127                 if ( this[0] && this[0].parentNode ) {
128                         return this.domManip(arguments, false, function( elem ) {
129                                 this.parentNode.insertBefore( elem, this );
130                         });
131                 } else if ( arguments.length ) {
132                         var set = jQuery(arguments[0]);
133                         set.push.apply( set, this.toArray() );
134                         return this.pushStack( set, "before", arguments );
135                 }
136         },
137
138         after: function() {
139                 if ( this[0] && this[0].parentNode ) {
140                         return this.domManip(arguments, false, function( elem ) {
141                                 this.parentNode.insertBefore( elem, this.nextSibling );
142                         });
143                 } else if ( arguments.length ) {
144                         var set = this.pushStack( this, "after", arguments );
145                         set.push.apply( set, jQuery(arguments[0]).toArray() );
146                         return set;
147                 }
148         },
149         
150         // keepData is for internal use only--do not document
151         remove: function( selector, keepData ) {
152                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
153                         if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
154                                 if ( !keepData && elem.nodeType === 1 ) {
155                                         jQuery.cleanData( elem.getElementsByTagName("*") );
156                                         jQuery.cleanData( [ elem ] );
157                                 }
158
159                                 if ( elem.parentNode ) {
160                                          elem.parentNode.removeChild( elem );
161                                 }
162                         }
163                 }
164                 
165                 return this;
166         },
167
168         empty: function() {
169                 for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
170                         // Remove element nodes and prevent memory leaks
171                         if ( elem.nodeType === 1 ) {
172                                 jQuery.cleanData( elem.getElementsByTagName("*") );
173                         }
174
175                         // Remove any remaining nodes
176                         while ( elem.firstChild ) {
177                                 elem.removeChild( elem.firstChild );
178                         }
179                 }
180                 
181                 return this;
182         },
183
184         clone: function( events ) {
185                 // Do the clone
186                 var ret = this.map(function() {
187                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
188                                 // IE copies events bound via attachEvent when
189                                 // using cloneNode. Calling detachEvent on the
190                                 // clone will also remove the events from the orignal
191                                 // In order to get around this, we use innerHTML.
192                                 // Unfortunately, this means some modifications to
193                                 // attributes in IE that are actually only stored
194                                 // as properties will not be copied (such as the
195                                 // the name attribute on an input).
196                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
197                                 if ( !html ) {
198                                         var div = ownerDocument.createElement("div");
199                                         div.appendChild( this.cloneNode(true) );
200                                         html = div.innerHTML;
201                                 }
202
203                                 return jQuery.clean([html.replace(rinlinejQuery, "")
204                                         // Handle the case in IE 8 where action=/test/> self-closes a tag
205                                         .replace(raction, '="$1">')
206                                         .replace(rleadingWhitespace, "")], ownerDocument)[0];
207                         } else {
208                                 return this.cloneNode(true);
209                         }
210                 });
211
212                 // Copy the events from the original to the clone
213                 if ( events === true ) {
214                         cloneCopyEvent( this, ret );
215                         cloneCopyEvent( this.find("*"), ret.find("*") );
216                 }
217
218                 // Return the cloned set
219                 return ret;
220         },
221
222         html: function( value ) {
223                 if ( value === undefined ) {
224                         return this[0] && this[0].nodeType === 1 ?
225                                 this[0].innerHTML.replace(rinlinejQuery, "") :
226                                 null;
227
228                 // See if we can take a shortcut and just use innerHTML
229                 } else if ( typeof value === "string" && !rnocache.test( value ) &&
230                         (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
231                         !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
232
233                         value = value.replace(rxhtmlTag, "<$1></$2>");
234
235                         try {
236                                 for ( var i = 0, l = this.length; i < l; i++ ) {
237                                         // Remove element nodes and prevent memory leaks
238                                         if ( this[i].nodeType === 1 ) {
239                                                 jQuery.cleanData( this[i].getElementsByTagName("*") );
240                                                 this[i].innerHTML = value;
241                                         }
242                                 }
243
244                         // If using innerHTML throws an exception, use the fallback method
245                         } catch(e) {
246                                 this.empty().append( value );
247                         }
248
249                 } else if ( jQuery.isFunction( value ) ) {
250                         this.each(function(i){
251                                 var self = jQuery(this), old = self.html();
252                                 self.empty().append(function(){
253                                         return value.call( this, i, old );
254                                 });
255                         });
256
257                 } else {
258                         this.empty().append( value );
259                 }
260
261                 return this;
262         },
263
264         replaceWith: function( value ) {
265                 if ( this[0] && this[0].parentNode ) {
266                         // Make sure that the elements are removed from the DOM before they are inserted
267                         // this can help fix replacing a parent with child elements
268                         if ( jQuery.isFunction( value ) ) {
269                                 return this.each(function(i) {
270                                         var self = jQuery(this), old = self.html();
271                                         self.replaceWith( value.call( this, i, old ) );
272                                 });
273                         }
274
275                         if ( typeof value !== "string" ) {
276                                 value = jQuery(value).detach();
277                         }
278
279                         return this.each(function() {
280                                 var next = this.nextSibling, parent = this.parentNode;
281
282                                 jQuery(this).remove();
283
284                                 if ( next ) {
285                                         jQuery(next).before( value );
286                                 } else {
287                                         jQuery(parent).append( value );
288                                 }
289                         });
290                 } else {
291                         return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
292                 }
293         },
294
295         detach: function( selector ) {
296                 return this.remove( selector, true );
297         },
298
299         domManip: function( args, table, callback ) {
300                 var results, first, value = args[0], scripts = [], fragment, parent;
301
302                 // We can't cloneNode fragments that contain checked, in WebKit
303                 if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
304                         return this.each(function() {
305                                 jQuery(this).domManip( args, table, callback, true );
306                         });
307                 }
308
309                 if ( jQuery.isFunction(value) ) {
310                         return this.each(function(i) {
311                                 var self = jQuery(this);
312                                 args[0] = value.call(this, i, table ? self.html() : undefined);
313                                 self.domManip( args, table, callback );
314                         });
315                 }
316
317                 if ( this[0] ) {
318                         parent = value && value.parentNode;
319
320                         // If we're in a fragment, just use that instead of building a new one
321                         if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
322                                 results = { fragment: parent };
323
324                         } else {
325                                 results = jQuery.buildFragment( args, this, scripts );
326                         }
327                         
328                         fragment = results.fragment;
329                         
330                         if ( fragment.childNodes.length === 1 ) {
331                                 first = fragment = fragment.firstChild;
332                         } else {
333                                 first = fragment.firstChild;
334                         }
335
336                         if ( first ) {
337                                 table = table && jQuery.nodeName( first, "tr" );
338
339                                 for ( var i = 0, l = this.length; i < l; i++ ) {
340                                         callback.call(
341                                                 table ?
342                                                         root(this[i], first) :
343                                                         this[i],
344                                                 i > 0 || results.cacheable || this.length > 1  ?
345                                                         fragment.cloneNode(true) :
346                                                         fragment
347                                         );
348                                 }
349                         }
350
351                         if ( scripts.length ) {
352                                 jQuery.each( scripts, evalScript );
353                         }
354                 }
355
356                 return this;
357         }
358 });
359
360 function root( elem, cur ) {
361         return jQuery.nodeName(elem, "table") ?
362                 (elem.getElementsByTagName("tbody")[0] ||
363                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
364                 elem;
365 }
366
367 function cloneCopyEvent(orig, ret) {
368         var i = 0;
369
370         ret.each(function() {
371                 if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
372                         return;
373                 }
374
375                 var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
376
377                 if ( events ) {
378                         delete curData.handle;
379                         curData.events = {};
380
381                         for ( var type in events ) {
382                                 for ( var handler in events[ type ] ) {
383                                         jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
384                                 }
385                         }
386                 }
387         });
388 }
389
390 jQuery.buildFragment = function( args, nodes, scripts ) {
391         var fragment, cacheable, cacheresults,
392                 doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
393
394         // Only cache "small" (1/2 KB) strings that are associated with the main document
395         // Cloning options loses the selected state, so don't cache them
396         // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
397         // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
398         if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
399                 !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
400
401                 cacheable = true;
402                 cacheresults = jQuery.fragments[ args[0] ];
403                 if ( cacheresults ) {
404                         if ( cacheresults !== 1 ) {
405                                 fragment = cacheresults;
406                         }
407                 }
408         }
409
410         if ( !fragment ) {
411                 fragment = doc.createDocumentFragment();
412                 jQuery.clean( args, doc, fragment, scripts );
413         }
414
415         if ( cacheable ) {
416                 jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
417         }
418
419         return { fragment: fragment, cacheable: cacheable };
420 };
421
422 jQuery.fragments = {};
423
424 jQuery.each({
425         appendTo: "append",
426         prependTo: "prepend",
427         insertBefore: "before",
428         insertAfter: "after",
429         replaceAll: "replaceWith"
430 }, function( name, original ) {
431         jQuery.fn[ name ] = function( selector ) {
432                 var ret = [], insert = jQuery( selector ),
433                         parent = this.length === 1 && this[0].parentNode;
434                 
435                 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
436                         insert[ original ]( this[0] );
437                         return this;
438                         
439                 } else {
440                         for ( var i = 0, l = insert.length; i < l; i++ ) {
441                                 var elems = (i > 0 ? this.clone(true) : this).get();
442                                 jQuery( insert[i] )[ original ]( elems );
443                                 ret = ret.concat( elems );
444                         }
445                 
446                         return this.pushStack( ret, name, insert.selector );
447                 }
448         };
449 });
450
451 jQuery.extend({
452         clean: function( elems, context, fragment, scripts ) {
453                 context = context || document;
454
455                 // !context.createElement fails in IE with an error but returns typeof 'object'
456                 if ( typeof context.createElement === "undefined" ) {
457                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
458                 }
459
460                 var ret = [];
461
462                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
463                         if ( typeof elem === "number" ) {
464                                 elem += "";
465                         }
466
467                         if ( !elem ) {
468                                 continue;
469                         }
470
471                         // Convert html string into DOM nodes
472                         if ( typeof elem === "string" && !rhtml.test( elem ) ) {
473                                 elem = context.createTextNode( elem );
474
475                         } else if ( typeof elem === "string" ) {
476                                 // Fix "XHTML"-style tags in all browsers
477                                 elem = elem.replace(rxhtmlTag, "<$1></$2>");
478
479                                 // Trim whitespace, otherwise indexOf won't work as expected
480                                 var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
481                                         wrap = wrapMap[ tag ] || wrapMap._default,
482                                         depth = wrap[0],
483                                         div = context.createElement("div");
484
485                                 // Go to html and back, then peel off extra wrappers
486                                 div.innerHTML = wrap[1] + elem + wrap[2];
487
488                                 // Move to the right depth
489                                 while ( depth-- ) {
490                                         div = div.lastChild;
491                                 }
492
493                                 // Remove IE's autoinserted <tbody> from table fragments
494                                 if ( !jQuery.support.tbody ) {
495
496                                         // String was a <table>, *may* have spurious <tbody>
497                                         var hasBody = rtbody.test(elem),
498                                                 tbody = tag === "table" && !hasBody ?
499                                                         div.firstChild && div.firstChild.childNodes :
500
501                                                         // String was a bare <thead> or <tfoot>
502                                                         wrap[1] === "<table>" && !hasBody ?
503                                                                 div.childNodes :
504                                                                 [];
505
506                                         for ( var j = tbody.length - 1; j >= 0 ; --j ) {
507                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
508                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
509                                                 }
510                                         }
511
512                                 }
513
514                                 // IE completely kills leading whitespace when innerHTML is used
515                                 if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
516                                         div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
517                                 }
518
519                                 elem = div.childNodes;
520                         }
521
522                         if ( elem.nodeType ) {
523                                 ret.push( elem );
524                         } else {
525                                 ret = jQuery.merge( ret, elem );
526                         }
527                 }
528
529                 if ( fragment ) {
530                         for ( i = 0; ret[i]; i++ ) {
531                                 if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
532                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
533                                 
534                                 } else {
535                                         if ( ret[i].nodeType === 1 ) {
536                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
537                                         }
538                                         fragment.appendChild( ret[i] );
539                                 }
540                         }
541                 }
542
543                 return ret;
544         },
545         
546         cleanData: function( elems ) {
547                 var data, id, cache = jQuery.cache,
548                         special = jQuery.event.special,
549                         deleteExpando = jQuery.support.deleteExpando;
550                 
551                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
552                         if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
553                                 continue;
554                         }
555
556                         id = elem[ jQuery.expando ];
557                         
558                         if ( id ) {
559                                 data = cache[ id ];
560                                 
561                                 if ( data && data.events ) {
562                                         for ( var type in data.events ) {
563                                                 if ( special[ type ] ) {
564                                                         jQuery.event.remove( elem, type );
565
566                                                 } else {
567                                                         jQuery.removeEvent( elem, type, data.handle );
568                                                 }
569                                         }
570                                 }
571                                 
572                                 if ( deleteExpando ) {
573                                         delete elem[ jQuery.expando ];
574
575                                 } else if ( elem.removeAttribute ) {
576                                         elem.removeAttribute( jQuery.expando );
577                                 }
578                                 
579                                 delete cache[ id ];
580                         }
581                 }
582         }
583 });
584
585 function evalScript( i, elem ) {
586         if ( elem.src ) {
587                 jQuery.ajax({
588                         url: elem.src,
589                         async: false,
590                         dataType: "script"
591                 });
592         } else {
593                 jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
594         }
595
596         if ( elem.parentNode ) {
597                 elem.parentNode.removeChild( elem );
598         }
599 }
600
601 })( jQuery );