Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

A simple jQuery Client Centering Plugin


:P
On this page:

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.

Posted in JavaScript  jQuery  

The Voices of Reason


 

Dave Ward
August 21, 2008

# re: A simple jQuery Client Centering Plugin

I like it! You should submit it to the jQuery plugins directory.

Ricky
August 21, 2008

# re: A simple jQuery Client Centering Plugin

Very cool Rick, i like it.

And I agree, submit it to the plugins repo :)

Christopher Steen
August 22, 2008

# Link Listing - August 21, 2008

Link Listing - August 21, 2008

Mehfuz Hossain
August 26, 2008

# re: A simple jQuery Client Centering Plugin

Cool, you just made my day !!!

ScobY9
October 11, 2008

# re: A simple jQuery Client Centering Plugin

thanks, now i don't have to write the code myself...

MIMI
January 28, 2009

# re: A simple jQuery Client Centering Plugin

Hi ,
it's perfect.
And I agree, submit it to the jquery plugins

vellu
February 27, 2009

# re: A simple jQuery Client Centering Plugin

For the latest jQuery version this part

        // 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!

Nils
March 02, 2009

# re: A simple jQuery Client Centering Plugin

I combined this with the window.resize() function to make a modal dialog always appeear dead center, regardless of window resizing and the dimensions of the container (which i need to be flexible), and it seems to work like a charm. thank you very much!

Josh Anderson
May 09, 2009

# re: A simple jQuery Client Centering Plugin

I made a modification that might help some people. In instances where the centered div is larger than the window size, the plugin as it exists now will position it above the top of the window, potentially rendering some contents inaccessible.

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

Rick Strahl
May 10, 2009

# re: A simple jQuery Client Centering Plugin

@Josh - great suggestions. Will integrate. Thanks!

@Nils - yup, I use it in my modalDialog plug-in as well for this purpose.

Francesco
May 19, 2009

# re: A simple jQuery Client Centering Plugin

Great job man!

prabhjot singh
May 21, 2009

# re: A simple jQuery Client Centering Plugin

Hi there,


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

Dalveer
May 22, 2009

# re: A simple jQuery Client Centering Plugin

HI Rick
Its Amazing Plugin BUt it is not working in mozilla PLease help


regards
dalveer

Rick Strahl
May 22, 2009

# re: A simple jQuery Client Centering Plugin

@Dalveer - sure does. More info please. It's probably better to post it over here with more information with your scenario:

http://www.west-wind.com/wwThreads/default.asp?Forum=West+Wind+Web+Toolkit+For+Asp.net

Dalveer
May 23, 2009

# re: A simple jQuery Client Centering Plugin

hi Rick..
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.

Dalveer
May 23, 2009

# re: A simple jQuery Client Centering Plugin

Hi Rick..

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.

AD
August 06, 2009

# re: A simple jQuery Client Centering Plugin

document.body.scrollTop() doesn't seem to work in ie8. I had to add this to calculate scrollTop....

var scrollTop = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;

AD

dsingh
August 10, 2009

# re: A simple jQuery Client Centering Plugin

Hi Rick ,
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.

Satish V
October 12, 2009

# re: A simple jQuery Client Centering Plugin

Hi Rick,

Thanks for this wonderful script. It was very helpful for me.

Satish V

Glenn
November 02, 2009

# re: A simple jQuery Client Centering Plugin

Hi Rick,

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

jaime
March 01, 2010

# re: A simple jQuery Client Centering Plugin

thank you, and a recommendation, use closure to allow use

$foo = jQuery.noConflict()

(function($) {
})(jQuery);

Pablo
June 14, 2010

# re: A simple jQuery Client Centering Plugin

Great! Thank you very much!!

ScooterT
July 15, 2010

# re: A simple jQuery Client Centering Plugin

Well done sir! That's pretty slick.

madmital
September 23, 2010

# re: A simple jQuery Client Centering Plugin

Actually the "forceAbsolute" will cause problems if used on an element in an asp.net page that contains server control(s).
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.

Michael Watson
December 20, 2011

# re: A simple jQuery Client Centering Plugin

Works great!! Saved me some time. Thank you very much Rick :)

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024