A simple jQuery Client Centering Plugin
In my client apps I often have a need to center elements in a browser window. Specifically when I have pop ups come up for the first time or when special status messages that are popped onto the screen during long operations, or modal dialogs pop up it's often necessary to have the content centered in the browser window. All of those operations tend to require some sort of centering of content at least in its default configuration.
I've had a centering routine for a while, but thought I should simplify by using jQuery and adding a few features like the ability to center content inside of other container elements on a page. There are already a couple of center like plugins available, but neither of the two I tried worked properly for centering content both horizontally and vertically in the main window including catching for scroll position.
One of the really nice things about jQuery is the ease with which you can extend jQuery's functionality via plug-ins. So I created a quick plug-in that does the centering job a lot more easily than my old code did and it's more flexible to boot.
Using the plug-in is as easy as:
$(document).ready(function() { $("#box").centerInClient(); });
which centers the element named box in the client window. To center the element inside of another container element you might use:
$("#box").centerInClient({ container: window, forceAbsolute: true });
Here's the code for my centerInClient plugin:
$.fn.centerInClient = function(options) { /// <summary>Centers the selected items in the browser window. Takes into account scroll position. /// Ideally the selected set should only match a single element. /// </summary> /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param> /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow /// and attached to the body element to ensure proper absolute positioning. /// Be aware that this may cause ID hierachy for CSS styles to be affected. /// </param> /// <returns type="jQuery" /> var opt = { forceAbsolute: false, container: window, // selector of element to center in completeHandler: null }; $.extend(opt, options); return this.each(function(i) { var el = $(this); var jWin = $(opt.container); var isWin = opt.container == window; // force to the top of document to ENSURE that // document absolute positioning is available if (opt.forceAbsolute) { if (isWin) el.remove().appendTo("body"); else el.remove().appendTo(jWin.get(0)); } // have to make absolute el.css("position", "absolute"); // height is off a bit so fudge it var heightFudge = isWin ? 2.0 : 1.8; var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2; var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2; el.css("left", x + jWin.scrollLeft()); el.css("top", y + jWin.scrollTop()); // if specified make callback and pass element if (opt.completeHandler) opt.completeHandler(this); }); }
The plug in can center elements either in the active window taking scroll positioning into account or center content inside of another container element.
There are several options available that can be passed using the option map.
container - optional container element to center in - defaults to window
forceAbsolute - forces the element to be centered to absolute positioning at the Body level. Use this if the element is already relatively positioned to another element and so force it to 'document' absolute positioning.
completeHandler - optional handler that is called when centering is complete. Use for trapping positioning notification.
I find this a handy feature to have around especially when working with pseudo windows and popups in client scripting.
The Voices of Reason
# re: A simple jQuery Client Centering Plugin
And I agree, submit it to the plugins repo :)
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
it's perfect.
And I agree, submit it to the jquery plugins
# re: A simple jQuery Client Centering Plugin
// force to the top of document to ENSURE that
// document absolute positioning is available
if (opt.forceAbsolute) {
if (isWin)
el.remove().appendTo("body");
else
el.remove().appendTo(jWin.get(0));
}should be updated like this
// force to the top of document to ENSURE that
// document absolute positioning is available
if (opt.forceAbsolute) {
if (isWin)
el.appendTo("body");
else
el.appendTo(jWin.get(0));
}Otherwise much appreciated!
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
First, I added two more options to the plugin - minX and minY:
var opt = { forceAbsolute: false, container: window, // selector of element to center in completeHandler: null, minX: 0, minY: 0 };
I then checked the final x and y positions to make sure they weren't outside those parameters:
el.css("left", x < opt.minX ? opt.minX + jWin.scrollLeft() : x + jWin.scrollLeft()); el.css("top", y < opt.minY ? opt.minY + jWin.scrollTop() : y + jWin.scrollTop());
This allows me to also set a buffer of sorts between the element and the window edges. For my use I set it at 10 so I have a 10px padding that I don't have to put on the body element or the centered div (since the padding might throw off the centering calcs anyway).
Josh
# re: A simple jQuery Client Centering Plugin
@Nils - yup, I use it in my modalDialog plug-in as well for this purpose.
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
I have implemented the pop up and it is showing perfectly, but the point is i want to show the pop up according to the position of the scroll bar, if the scroll bar is down at the bottom, the pop up should open at the center of page.
In the above case if i drag the scroll bar to the bottom of the page, then also the pop up opens on top. what should i do???
Regards
Prabhjot singh
# re: A simple jQuery Client Centering Plugin
Its Amazing Plugin BUt it is not working in mozilla PLease help
regards
dalveer
# re: A simple jQuery Client Centering Plugin
http://www.west-wind.com/wwThreads/default.asp?Forum=West+Wind+Web+Toolkit+For+Asp.net
# re: A simple jQuery Client Centering Plugin
Thanks for reply.
I have post message on Messageboard.
this plugging is not calling in Mozilla.
Thie following code is not executing in case of mozila so not calling centerInClient plugin.
$(document).ready(function() {
$("#box").centerInClient();
});
Is there is any different or extra code for mozilla?
Please help.
Thanks and regards
Dalveer.
# re: A simple jQuery Client Centering Plugin
Can you help me that how can i place the item in center according to the scrol position. Means if i scroling to up/down of browser window then this pop up or item should move to up/down but should remaining in center of browser window.
Thanks and Regards
dalveer.
# re: A simple jQuery Client Centering Plugin
var scrollTop = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
AD
# re: A simple jQuery Client Centering Plugin
this pluging is very helpful for me. but there is a problem that i have a iframe on a page and this pliging open the popup in the center of iframe. i wants to open this popup in this iframe according to the browser scrol position. Can u help me to do this.
regards
dsingh.
# re: A simple jQuery Client Centering Plugin
Thanks for this wonderful script. It was very helpful for me.
Satish V
# re: A simple jQuery Client Centering Plugin
Awesome script, just what I needed. Could you also demonstrate how to use with the resize() function so it stays centered even when someone tries to resize the page? Thanks in advance!
-Glenn
# re: A simple jQuery Client Centering Plugin
$foo = jQuery.noConflict()
(function($) {
})(jQuery);
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
# re: A simple jQuery Client Centering Plugin
The postback functionality of a control is broken if it is moved outside of the form element.
For example this won't work. The button postback event will stop triggering:
<body>
<form id="form1" runat="server">
<div id="divWithButton" style="border:solid 1px #ff0000;width:200px;height:300px;">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() { $("#divWithButton").centerInClient( {forceAbsolute:true} ); });
</script>
</body>
For this to work properly in asp.net-context the element being centered should be appended to the asp.net form element instead of the body element.
# re: A simple jQuery Client Centering Plugin