el.severo
el.severo

Reputation: 2287

Set the popup window to center jquery

Right now I'm setting the position of the modal jQuery window in this way:

   var winH = $(window).height();
   var winW = $(window).width();
    //Set the popup window to center
    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);

How do I center the popUp when I scroll down?

Upvotes: 7

Views: 43794

Answers (4)

Ken Shiro
Ken Shiro

Reputation: 719

This one is helped me!

$.fn.center = function() {
    this.css("position", "fixed");
    this.css("top", ($(window).height()/2 - this.height()/2) + "px");
    this.css("left", ($(window).width()/2 - this.width()/2) + "px");
    return this;
}

And use as described.

$(".modal-window").center();

Upvotes: 4

arifur rahman
arifur rahman

Reputation: 264

you can use this in this way

// Position modal box in the center of the page

    jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");
    this.css("left", ( jQuery(window).width() - this.width() ) / 2+jQuery(window).scrollLeft() + "px");
    return this;
  }

//then call the function

 jQuery(".modal-profile").center();

and this will make your code organized and easy to use in any project for center the modal. you can view this kind of work in another question

modal appears on page load

Upvotes: 6

pete
pete

Reputation: 25091

Assuming you're using the jQuery UI Dialog, the default position is 'center' which centers it in the viewport by default. If you're using a different jQuery modal window, then:

$(id).css({
    'position': 'fixed',
    'top': parseInt((winH / 2) - ($(id).height() / 2), 10)
    'left': parseInt((winW / 2) - ($(id).width() / 2), 10)
});

might do the trick. I'm not sure what you mean by "scroll down" as a modal dialog and scrolling (outside the dialog) are mutually exclusive.

Upvotes: 1

Mike L.
Mike L.

Reputation: 1966

You could just use another CSS style, try position: fixed

Upvotes: 8

Related Questions