Created
December 2, 2009 14:04
-
-
Save diago/247214 to your computer and use it in GitHub Desktop.
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
/** | |
* Methods for extending Prototype | |
*/ | |
var Position = { | |
/** | |
* Centers an element against the parent or body | |
* parent should be display: relative | |
*/ | |
center: function(elem, parent){ | |
var elem = $(elem), | |
dims = elem.getDimensions(), | |
scroll = document.viewport.getScrollOffsets(), | |
bgDims, top, left; | |
// are we using a parent? | |
if(parent) bgDims = $(parent).getDimensions(); | |
else bgDims = document.viewport.getDimensions(); | |
top = parseInt( ( ( ( bgDims.height ) - dims.height) / 2 ), 10); | |
left = parseInt( ( ( ( bgDims.width ) - dims.width) / 2 ), 10 ); | |
elem.setStyle({ | |
position: 'absolute', | |
top: top + scroll.top + 'px', | |
left: left + scroll.left + 'px' | |
}); | |
return elem; | |
}, | |
/** | |
* Used to keep ensure an element stays within a scrollable div | |
*/ | |
keepWithin: function(elem, parent, padding){ | |
elem = $(elem); | |
parent = $(parent); | |
padding = padding || 0; | |
// return if no scrollbars | |
if(parent.scrollHeight < 1) return elem; | |
var elemViewportBottom = elem.getBoundingClientRect().bottom.ceil(); | |
var parentViewportBottom = parent.viewportOffset().top + parent.getHeight(); | |
if(parentViewportBottom < elemViewportBottom) | |
parent.scrollTop = elemViewportBottom - parentViewportBottom + padding; | |
return elem; | |
} | |
}; | |
Element.addMethods(Position); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment