Skip to content

Instantly share code, notes, and snippets.

@osdrv
Created May 29, 2013 17:39
Show Gist options
  • Save osdrv/5672193 to your computer and use it in GitHub Desktop.
Save osdrv/5672193 to your computer and use it in GitHub Desktop.
Tiny jQuery tool to pin absolute-positioned div in current screen position and unpin it back
;(function() {
var FIXED = 'fixed';
var ABSOLUTE = 'absolute';
var $w = $(window);
window.pin = function(obj) {
var objPos = obj.css('position');
if (objPos == FIXED) return;
var objOffset = obj.offset();
var objPos = obj.position();
var scrollTop = $w.scrollTop();
var scrollLeft = $w.scrollLeft();
obj.attr({
posX: objPos.left - scrollLeft,
posY: objPos.top - scrollTop
}).css({
position: FIXED,
left: objOffset.left - scrollLeft,
top: objOffset.top - scrollTop
});
}
window.unpin = function(obj) {
var objPos = obj.css('position');
if (objPos == ABSOLUTE) return;
var objOffset = obj.offset();
var objPos = obj.position();
var originalPosX = obj.attr('posX')|0;
var originalPosY = obj.attr('posY')|0;
obj.css({
position: ABSOLUTE,
left: objOffset.left - objPos.left + originalPosX,
top: objOffset.top - objPos.top + originalPosY
});
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment