Center 2.0
Created Wednesday 17th of September 2008 by Andreas Lagerkvist
Copyright © 2008 Andreas Lagerkvist (andreaslagerkvist.com)
Please have a look at the "Other Resources" for bug reports or further help on jQuery. Do not post bug reports or feature requests as comments to unrelated articles. If bug reporting on bugtracker.a-framework.org fails, e-mail me.
What it Does
This little pluggy centers an element on the screen using either fixed or absolute positioning. Can be used to display messages, pop up images etc.
How to Use
jQuery('#my-element').center(true); would center the element with ID 'my-element' using absolute position (leave empty for fixed).
Example
I should be fixed centered
The paragraph above and the paragraph beneath this one are centered. They should be in the middle of the viewport.
I should be absolutely centered
Example Code
HTML
<div id="jquery-center-example">
<p>I should be fixed centered</p>
<p>The paragraph above and the paragraph beneath this one are centered. They should be in the middle of the viewport.</p>
<p>I should be absolutely centered</p>
</div>
JS
jQuery('#jquery-center-example p:first-child').center();
jQuery('#jquery-center-example p:last-child').center(true);
Source Code
jQuery.fn.center = function (absolute) {
return this.each(function () {
var t = jQuery(this);
t.css({
position: absolute ? 'absolute' : 'fixed',
left: '50%',
top: '50%',
zIndex: '99'
}).css({
marginLeft: '-' + (t.outerWidth() / 2) + 'px',
marginTop: '-' + (t.outerHeight() / 2) + 'px'
});
if (absolute) {
t.css({
marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
});
}
});
};
Random jQuery Plug-ins
Ajax Loader
Use this plug-in when you want to inform your visitors that a certain part of your page is currently loading. The plug-in adds a faded 'loading-div' o...
Drag to Select
Use this plug-in to allow your users to select certain elements by dragging a "select box". Works very similar to how you can drag-n-select files and ...
Vibrate
This plug-in makes any element you want "vibrate" every now and then. Can be used in conjunction with blink for maximum annoyance!