Can you explain the following logic inside "if ( jQuery.isFunction( value ))" inside addClass? I don't understand what its purpose. Thanks.
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
Have a look at the API page. You'll see that there is a way of calling addClass
that passes a function as the first argument. The function receives the element and returns class names to be added:
A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments. Within the function,
this
refers to the current element in the set.
So you can do this:
$('.someElements').addClass(function(i, currentClass) {
return 'newClass' + i;
});
The first element selected will have the class newClass0
added, the second newClass1
, etc.
With the code you posted:
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
This says:
this
value), the position in the loop as the first argument and the className
property as the second argument).addClass
method with the result of step #3.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With