SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,053
    Mentioned
    66 Post(s)
    Tagged
    1 Thread(s)

    Prototype Element.center 1.6+

    This code takes an element, makes it's positioning absolute, centers it, then returns the element.

    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);
    Thereafter $('divID').center(); will center the div with id 'divID'.

    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.
    Last edited by Michael Morris; Feb 24, 2008 at 21:40.

  2. #2
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ooooooook.

    Does the function take into account elements whose position is fixed?

  3. #3
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,053
    Mentioned
    66 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by SoulScratch View Post
    ooooooook.

    Does the function take into account elements whose position is fixed?
    I haven't tested it with anything other than divs. You could pass the element through absolutize though to address this - or add the line to the function above to combine them. e.g.

    $('element').absolutize().center()


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •