jQuery.swap
2/19/2011
Having recently delved into the deeper tunnels of the css component of the jQuery source, I had discovered a surprisingly useful internal jQuery function that may be of use to you: jQuery.swap. I’m sure we’ve all encountered issues retrieving consistent cross-browser css values with javascript. I have written this function dozens of times and not realized that it was already in jQuery.
Check out the source for swap.
To demonstrate, I wrote a lightbox plugin for a site and needed to calculate it’s final position when opened. It does a flip css3 animation while expanding from a given point. I attach the necessary html for the lightbox given certain parameters on what content it should pull in and which element (an anchor) will be clicked to open it. The lightbox is inserted after the anchor and by default, the lightbox expands as if out from behind the anchor it is attached to.
Having attached the lightbox, I want to allow the user to override it’s original position in their own css, so in order to retrieve accurate top/left values in Firefox 3, the lightbox could not be hidden or I would consistently get back 0.
var $lightbox = $('#lightbox'),
top, left;
// Temporarily swap visibility instead of display: none to get correct top/left in firefox 3
$.swap($lightbox[0],
{ "display" : "block",
"visibility": "hidden" },
function() {
top = $lightbox.css('top');
left = $lightbox.css('left');
});