How to reposition my jQuery popup?

I've got a popup working with jQuery but it is rendering at the same place as the DIV. I'd like the popup to render in the middle of the page. Is it possible? If yes, then how?

My CSS:

.newpopup {
    display:none;
    border: 1px solid black;
    background-color: #eee;
}

HTML:

 <div class='newpopup'>
</div>
<button>popup</button>

JavaScript:

function popup() {
    alert('test');
    var popup = $('.newpopup');
    popup.draggable();
    popup.resizable();
    popup.html('<p>Where is pancakes house?</p>');
    popup.show('fast');
}
$(document).ready(function(){
  $('button').click(function(){
     popup();
  });
})

Answers


Set your popup css position : absolute and use top & left properties to set your popup position.

  .newpopup {
    display:none;
    border: 1px solid black;
    background-color: #eee;
    position:absolute;
    top:50%;
    left:50%;
}

EDIT

I created a fiddle , Jsfiddle it works perfectly here, check it out.


You need to get the width and height of the screen, and the box you've created

var screen_width = $(document).width();
var screen_height = $(document).height();
var box_width = popup.width();
var box_height = popup.height();

You then need to set position:absolute; on .newpopup. As well as it's top and left positions

var top = (screen_height - box_height) / 2; // you might like to subtract a little to position it slightly higher than half way
var left = (screen_width - box_width) / 2;
popup.css({ 'position': 'absolute', 'top':top, 'left':left });

The code can be condensed, but it's easier to understand split up.

Edit: You can add the pop-up box to the start of the page by using $(body).prepend(popup);, which will mean it does not get affected by any other element


Need Your Help

how to configure cakephp in nginx

cakephp nginx memcached centos vhosts

Currently i am working on cakephp with nginx. I setup a cakephp environment on a Centos server running Nginx with Fact CGI. The problem is that I cannot get the rewrite rules to setup correct in my...

Populate form with previous data

javascript php jquery laravel-5.1

I'm looking to add a feature to my application which currently, you enter your first name and last name and a few other details.