0

I'm running into a bug where my modal won't open in the center window. The code i'm currently using to measure the middle is the following:

var id = j('#share-modal');

// show modal, resize
j(id).css('top',  j(window).height()/2-j(id).height()/2);                 
j(id).css('left', j(window).width()/2-j(id).width()/2);

j('#share-modal').fadeIn(500);


 CSS

#share-modal {
    display: none;
    font-family: Arial, sans-serif;
    width: 537px;
    height: 510px;
    position: absolute;
    background: #FFF;
    z-index: 100;
    box-shadow: 3px 3px 3px #333;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
}

This is the only code I put that is supposed to be centering the code, but I can't tell if something else is interfering.

View my Javascript here: http://pastebin.com/wZeY5azT

You can view it here: www.paultibbs.com/varier

Scroll down and click on the "Share with friend" button.

If anyone can help me solve this bug, i'd be greatly appreciated!

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Firstly why j instead of the more common $ as the convention is? ;-) It actually **is** in the **dead center** of the window (if you scroll that page all the way up, you will see what I mean). What you really want is the center of the currently displayed area of the document actually. So, use y-axis position relative to where the click event was or the button is. – Ustaman Sangat Feb 10 '12 at 02:33
  • @UstamanSangat how about up voting existing answers instead of just repeating what was said 6 minutes ago? – thenetimp Feb 10 '12 at 02:34
  • You don't have to worry about it in this specific case, but bear in mind that if you have a border, margin or padding on your modal box you MUST either compensate for them in your positioning, OR use `box-sizing: border-box;`. – Niet the Dark Absol Feb 10 '12 at 02:37
  • @thenetimp,when I started writing the answer there wasn't any to upvote, trust me look at my timestamp. :-( – Ustaman Sangat Feb 10 '12 at 02:37

2 Answers2

1

You need to take into account the scroll position.

// Add the pageYOffset should fix the problem
j(id).css('top',  (j(window).height()/2-j(id).height()/2) + window.pageYOffset);

You'll also have to maintain watch on the scroll event and regenerate the position in case they scroll up and down.

thenetimp
  • 9,487
  • 5
  • 29
  • 42
  • great, since you're new to Stackoverflow, when someone gives you the right answer you accept it. It gives you reputation and it also gives them reputation. – thenetimp Feb 10 '12 at 08:12
1

From jQuery Docs:

var height = $(window).height();
var scrollTop = $(window).scrollTop();

http://docs.jquery.com/CSS/scrollTop
http://docs.jquery.com/CSS/height

via How do I determine height and scrolling position of window in jQuery?

Community
  • 1
  • 1
JSuar
  • 21,056
  • 4
  • 39
  • 83