Saturday, October 15, 2011

How to align in center your modal page in jQuery

I have created a jQuery function that will align your modal page in center. The alignment will default to "0" if it encounters a negative value.

Please see below script.

$.fn.doCenter = function () {
    var topVal = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
    var leftVal = (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft();

    if (topVal < 0) topVal = 0;
    if (leftVal < 0) leftVal = 0;

    this.css("position","absolute");
    this.css("top", topVal + "px");
    this.css("left", leftVal + "px");

    return this;
}


Sample usage:

$("#yourmodal").doCenter();


Give it a try, you will love it!!

No comments:

Post a Comment