This code takes an element, makes it's positioning absolute, centers it, then returns the element.
Thereafter $('divID').center(); will center the div with id 'divID'.Code:ElementExtensions: { center: function ( element, limitX, limitY ) { element = $(element); var elementDims = element.getDimensions(); var viewPort = document.viewport.getDimensions(); var offsets = document.viewport.getScrollOffsets(); var centerX = viewPort.width / 2 + offsets.left - elementDims.width / 2; var centerY = viewPort.height / 2 + offsets.top - elementDims.height / 2; if ( limitX && centerX < limitX ) { centerX = parseInt(limitX); } if ( limitY && centerY < limitY ) { centerY = parseInt(limitY); } element.setStyle( { position: 'absolute', top: Math.floor(centerY) + 'px', left: Math.floor(centerX) + 'px' } ); return element; } } Element.addMethods(ElementExtensions);
This code requires prototype 1.6+
EDIT: The limit calls are to make sure that especially large elements don't get positioned with their top and left margins off screen. You can use them to set a minimum distance from the top and left for the element. For example
$('divId').center(100, 100);
will center the element unless it is so large that it would be no closer than 100 pixels to the top or left. In that event it places the element 100 pixels away from those edges.






Bookmarks