Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created March 29, 2012 07:33
Show Gist options
  • Save s-hiroshi/2234564 to your computer and use it in GitHub Desktop.
Save s-hiroshi/2234564 to your computer and use it in GitHub Desktop.
jQuery > plugin > layout element to center
/**
*
* layout element to center for targettarget
*
* @param {jQuery} target optional
* @param {String} type optional vertical, horizonal, all
* @return jQuery Object
*/
jQuery.fn.setCenter = function(target, type) {
target = target || $(window);
target = (target instanceof jQuery) ? target : $(target);
if (target.get(0).tagName === 'HTML' || target.get(0).tagName === 'BODY') {
target = $(window);
}
// size
var width = $(this).width();
var height = $(this).height();
// target element size
var targetWidth = target.width();
var targetHeight = target.height();
if (target.get(0) != window) {
var targetCssPos;
// target element position
targetCssPos = target.css('position');
if ((targetCssPos != 'absolute') && (targetCssPos != 'relative')) {
target.css({
position: 'relative'
});
}
}
// offset
var offsetX = Math.ceil((targetWidth - width) / 2);
var offsetY = Math.ceil((targetHeight - height) / 2);
// type vertical, horizonal, all
type = type || 'all';
// position property
var pos = {
position: 'absolute'
};
if (type == 'vertical' || type == 'all') {
pos.top = offsetY;
}
if (type == 'horizonal' || type == 'all') {
pos.left = offsetX;
}
// layout center
$(this).css(pos);
return $(this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment