Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about jQuery source code (addClass)

Tags:

jquery

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;
    },
like image 697
Ricky Avatar asked Sep 13 '11 12:09

Ricky


1 Answers

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:

  1. If the first argument was a function
  2. Loop through all the elements selected
  3. For each of them, call the function with the element as the context (the this value), the position in the loop as the first argument and the className property as the second argument).
  4. Then call the addClass method with the result of step #3.
like image 199
lonesomeday Avatar answered Sep 20 '22 10:09

lonesomeday