Created
May 29, 2013 17:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(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