7690c81176ecfae10c354cfca61810a6641da80f
[jquery.git] / src / attributes.js
1 // exclude the following css properties to add px
2 var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
3         // cache defaultView
4         defaultView = document.defaultView || {};
5
6 jQuery.fn.extend({
7         attr: function( name, value, type ) {
8                 var options = name, isFunction = jQuery.isFunction( value );
9
10                 // Look for the case where we're accessing a style value
11                 if ( typeof name === "string" ) {
12                         if ( value === undefined ) {
13                                 return this.length ?
14                                         jQuery[ type || "attr" ]( this[0], name ) :
15                                         null;
16
17                         } else {
18                                 options = {};
19                                 options[ name ] = value;
20                         }
21                 }
22
23                 // Check to see if we're setting style values
24                 for ( var i = 0, l = this.length; i < l; i++ ) {
25                         var elem = this[i];
26
27                         // Set all the styles
28                         for ( var prop in options ) {
29                                 value = options[prop];
30
31                                 if ( isFunction ) {
32                                         value = value.call( elem, i );
33                                 }
34
35                                 if ( typeof value === "number" && type === "curCSS" && !exclude.test(prop) ) {
36                                         value = value + "px";
37                                 }
38
39                                 jQuery.attr( type ? elem.style : elem, prop, value );
40                         }
41                 }
42
43                 return this;
44         },
45
46         css: function( key, value ) {
47                 // ignore negative width and height values
48                 if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
49                         value = undefined;
50                 return this.attr( key, value, "curCSS" );
51         },
52
53         hasClass: function( selector ) {
54                 return !!selector && this.is( "." + selector );
55         },
56
57         val: function( value ) {
58                 if ( value === undefined ) {
59                         var elem = this[0];
60
61                         if ( elem ) {
62                                 if( jQuery.nodeName( elem, 'option' ) )
63                                         return (elem.attributes.value || {}).specified ? elem.value : elem.text;
64                                 
65                                 // We need to handle select boxes special
66                                 if ( jQuery.nodeName( elem, "select" ) ) {
67                                         var index = elem.selectedIndex,
68                                                 values = [],
69                                                 options = elem.options,
70                                                 one = elem.type == "select-one";
71
72                                         // Nothing was selected
73                                         if ( index < 0 )
74                                                 return null;
75
76                                         // Loop through all the selected options
77                                         for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
78                                                 var option = options[ i ];
79
80                                                 if ( option.selected ) {
81                                                         // Get the specifc value for the option
82                                                         value = jQuery(option).val();
83
84                                                         // We don't need an array for one selects
85                                                         if ( one )
86                                                                 return value;
87
88                                                         // Multi-Selects return an array
89                                                         values.push( value );
90                                                 }
91                                         }
92
93                                         return values;                          
94                                 }
95
96                                 // Everything else, we just grab the value
97                                 return (elem.value || "").replace(/\r/g, "");
98
99                         }
100
101                         return undefined;
102                 }
103
104                 if ( typeof value === "number" )
105                         value += '';
106
107                 return this.each(function(){
108                         if ( this.nodeType != 1 )
109                                 return;
110
111                         if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
112                                 this.checked = (jQuery.inArray(this.value, value) >= 0 ||
113                                         jQuery.inArray(this.name, value) >= 0);
114
115                         else if ( jQuery.nodeName( this, "select" ) ) {
116                                 var values = jQuery.makeArray(value);
117
118                                 jQuery( "option", this ).each(function(){
119                                         this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
120                                                 jQuery.inArray( this.text, values ) >= 0);
121                                 });
122
123                                 if ( !values.length )
124                                         this.selectedIndex = -1;
125
126                         } else
127                                 this.value = value;
128                 });
129         }
130 });
131
132 jQuery.each({
133         removeAttr: function( name ) {
134                 jQuery.attr( this, name, "" );
135                 if (this.nodeType == 1)
136                         this.removeAttribute( name );
137         },
138
139         addClass: function( classNames ) {
140                 jQuery.className.add( this, classNames );
141         },
142
143         removeClass: function( classNames ) {
144                 jQuery.className.remove( this, classNames );
145         },
146
147         toggleClass: function( classNames, state ) {
148                 if( typeof state !== "boolean" )
149                         state = !jQuery.className.has( this, classNames );
150                 jQuery.className[ state ? "add" : "remove" ]( this, classNames );
151         }
152 }, function(name, fn){
153         jQuery.fn[ name ] = function(){
154                 return this.each( fn, arguments );
155         };
156 });
157
158 jQuery.extend({
159         className: {
160                 // internal only, use addClass("class")
161                 add: function( elem, classNames ) {
162                         jQuery.each((classNames || "").split(/\s+/), function(i, className){
163                                 if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
164                                         elem.className += (elem.className ? " " : "") + className;
165                         });
166                 },
167
168                 // internal only, use removeClass("class")
169                 remove: function( elem, classNames ) {
170                         if (elem.nodeType == 1)
171                                 elem.className = classNames !== undefined ?
172                                         jQuery.grep(elem.className.split(/\s+/), function(className){
173                                                 return !jQuery.className.has( classNames, className );
174                                         }).join(" ") :
175                                         "";
176                 },
177
178                 // internal only, use hasClass("class")
179                 has: function( elem, className ) {
180                         return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
181                 }
182         },
183
184         // A method for quickly swapping in/out CSS properties to get correct calculations
185         swap: function( elem, options, callback ) {
186                 var old = {};
187                 // Remember the old values, and insert the new ones
188                 for ( var name in options ) {
189                         old[ name ] = elem.style[ name ];
190                         elem.style[ name ] = options[ name ];
191                 }
192
193                 callback.call( elem );
194
195                 // Revert the old values
196                 for ( var name in options )
197                         elem.style[ name ] = old[ name ];
198         },
199
200         css: function( elem, name, force, extra ) {
201                 if ( name == "width" || name == "height" ) {
202                         var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
203
204                         function getWH() {
205                                 val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
206
207                                 if ( extra === "border" )
208                                         return;
209
210                                 jQuery.each( which, function() {
211                                         if ( !extra )
212                                                 val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
213                                         if ( extra === "margin" )
214                                                 val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
215                                         else
216                                                 val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
217                                 });
218                         }
219
220                         if ( elem.offsetWidth !== 0 )
221                                 getWH();
222                         else
223                                 jQuery.swap( elem, props, getWH );
224
225                         return Math.max(0, Math.round(val));
226                 }
227
228                 return jQuery.curCSS( elem, name, force );
229         },
230
231         curCSS: function( elem, name, force ) {
232                 var ret, style = elem.style;
233
234                 // We need to handle opacity special in IE
235                 if ( name == "opacity" && !jQuery.support.opacity ) {
236                         ret = jQuery.attr( style, "opacity" );
237
238                         return ret == "" ?
239                                 "1" :
240                                 ret;
241                 }
242
243                 // Make sure we're using the right name for getting the float value
244                 if ( name.match( /float/i ) )
245                         name = styleFloat;
246
247                 if ( !force && style && style[ name ] )
248                         ret = style[ name ];
249
250                 else if ( defaultView.getComputedStyle ) {
251
252                         // Only "float" is needed here
253                         if ( name.match( /float/i ) )
254                                 name = "float";
255
256                         name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
257
258                         var computedStyle = defaultView.getComputedStyle( elem, null );
259
260                         if ( computedStyle )
261                                 ret = computedStyle.getPropertyValue( name );
262
263                         // We should always get a number back from opacity
264                         if ( name == "opacity" && ret == "" )
265                                 ret = "1";
266
267                 } else if ( elem.currentStyle ) {
268                         var camelCase = name.replace(/\-(\w)/g, function(all, letter){
269                                 return letter.toUpperCase();
270                         });
271
272                         ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
273
274                         // From the awesome hack by Dean Edwards
275                         // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
276
277                         // If we're not dealing with a regular pixel number
278                         // but a number that has a weird ending, we need to convert it to pixels
279                         if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
280                                 // Remember the original values
281                                 var left = style.left, rsLeft = elem.runtimeStyle.left;
282
283                                 // Put in the new values to get a computed value out
284                                 elem.runtimeStyle.left = elem.currentStyle.left;
285                                 style.left = ret || 0;
286                                 ret = style.pixelLeft + "px";
287
288                                 // Revert the changed values
289                                 style.left = left;
290                                 elem.runtimeStyle.left = rsLeft;
291                         }
292                 }
293
294                 return ret;
295         },
296
297         attr: function( elem, name, value ) {
298                 // don't set attributes on text and comment nodes
299                 if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
300                         return undefined;
301
302                 var notxml = !elem.tagName || !jQuery.isXMLDoc( elem ),
303                         // Whether we are setting (or getting)
304                         set = value !== undefined;
305
306                 // Try to normalize/fix the name
307                 name = notxml && jQuery.props[ name ] || name;
308
309                 // Only do all the following if this is a node (faster for style)
310                 // IE elem.getAttribute passes even for style
311                 if ( elem.tagName ) {
312
313                         // These attributes require special treatment
314                         var special = /href|src|style/.test( name );
315
316                         // Safari mis-reports the default selected property of a hidden option
317                         // Accessing the parent's selectedIndex property fixes it
318                         if ( name == "selected" && elem.parentNode )
319                                 elem.parentNode.selectedIndex;
320
321                         // If applicable, access the attribute via the DOM 0 way
322                         if ( name in elem && notxml && !special ) {
323                                 if ( set ){
324                                         // We can't allow the type property to be changed (since it causes problems in IE)
325                                         if ( name == "type" && elem.nodeName.match(/(button|input)/i) && elem.parentNode )
326                                                 throw "type property can't be changed";
327
328                                         elem[ name ] = value;
329                                 }
330
331                                 // browsers index elements by id/name on forms, give priority to attributes.
332                                 if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
333                                         return elem.getAttributeNode( name ).nodeValue;
334
335                                 // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
336                                 // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
337                                 if ( name == "tabIndex" ) {
338                                         var attributeNode = elem.getAttributeNode( "tabIndex" );
339                                         return attributeNode && attributeNode.specified
340                                                 ? attributeNode.value
341                                                 : elem.nodeName.match(/(button|input|object|select|textarea)/i)
342                                                         ? 0
343                                                         : elem.nodeName.match(/^(a|area)$/i) && elem.href
344                                                                 ? 0
345                                                                 : undefined;
346                                 }
347
348                                 return elem[ name ];
349                         }
350
351                         if ( !jQuery.support.style && notxml &&  name == "style" )
352                                 return jQuery.attr( elem.style, "cssText", value );
353
354                         if ( set )
355                                 // convert the value to a string (all browsers do this but IE) see #1070
356                                 elem.setAttribute( name, "" + value );
357
358                         var attr = !jQuery.support.hrefNormalized && notxml && special
359                                         // Some attributes require a special call on IE
360                                         ? elem.getAttribute( name, 2 )
361                                         : elem.getAttribute( name );
362
363                         // Non-existent attributes return null, we normalize to undefined
364                         return attr === null ? undefined : attr;
365                 }
366
367                 // elem is actually elem.style ... set the style
368
369                 // IE uses filters for opacity
370                 if ( !jQuery.support.opacity && name == "opacity" ) {
371                         if ( set ) {
372                                 // IE has trouble with opacity if it does not have layout
373                                 // Force it by setting the zoom level
374                                 elem.zoom = 1;
375
376                                 // Set the alpha filter to set the opacity
377                                 elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
378                                         (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
379                         }
380
381                         return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
382                                 (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
383                                 "";
384                 }
385
386                 name = name.replace(/-([a-z])/ig, function(all, letter){
387                         return letter.toUpperCase();
388                 });
389
390                 if ( set )
391                         elem[ name ] = value;
392
393                 return elem[ name ];
394         }
395 });