0

Browsing through the source of 1.7rc1, line 6625, I've found the .swap function:

// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
    var old = {};

    // Remember the old values, and insert the new ones
    for ( var name in options ) {
        old[ name ] = elem.style[ name ];
        elem.style[ name ] = options[ name ];
    }

    callback.call( elem );

    // Revert the old values
    for ( name in options ) {
        elem.style[ name ] = old[ name ];
    }
}

I've never seen it used before. Do people actually use it? For what?

Randomblue
  • 112,777
  • 145
  • 353
  • 547

1 Answers1

1

.swap(elem, options, callback) is a function that temporarily sets a number of CSS values (those passed in object of the 2nd argument), calls the callback (the 3rd argument) and then restores the original CSS values after the callback returns.

jQuery uses it for temporarily changing the layout of things in order to do some measurements. For example, if you take a div object and set it to position: absolute, you will be able to get it's true width, but if it's in the normal layout of the document, a div takes the width of it's container. If you step through a jQuery call to .width() or look at how that function is implemented in the source, you will see it being used.

I'm sure you could invent/find something else to use it for, but I've not found a need for it other than the measurement types of use that jQuery is using it for.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
jfriend00
  • 683,504
  • 96
  • 985
  • 979