Home > Blockchain >  Understand the code snippet in jQuery offset method
Understand the code snippet in jQuery offset method

Time:10-19

I am trying to studying the jQuery method of offset, as below:

    // offset() relates an element's border box to the document origin
    offset: function( options ) {

        // Preserve chaining for setter
        if ( arguments.length ) {
            return options === undefined ?
                this :
                this.each( function( i ) {
                    jQuery.offset.setOffset( this, options, i );
                } );
        }
...

I cannot understand the first paragraph very well. It seems that the method is to check if there are any arguments, and if yes, it will check options, if no options provided, just return the current object, if any options is defined, it will set offset(that is rather strange since this function is to get offset, not to set offset).

CodePudding user response:

.offset can be used in two ways: to get the offset, or to set the offset. See the docs.

When called with no arguments, it will:

Description: Get the current coordinates of the first element in the set of matched elements, relative to the document.

Hence the check for arguments.length.

When called with an argument, it will:

.offset( coordinates )

Description: Set the current coordinates of every element in the set of matched elements, relative to the document.

Which is why the code does

if (arguments.length) {
  // set offset of matching elements and return
}
// get and return offset of first matching element
  • Related