Skip to content

Instantly share code, notes, and snippets.

@diago
Created December 2, 2009 14:04
Show Gist options
  • Save diago/247214 to your computer and use it in GitHub Desktop.
Save diago/247214 to your computer and use it in GitHub Desktop.
/**
* 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