4

I'm trying to create a simple modal popup. I have the CSS done, and the Javascript mostly done. I'm at the point where I click a button at the button of the page and the popup appears, but it appears at the top of the page. It appears excatly how it should if you were scrolled all the way to the top of the page.

I however want the modal popup box to appear center based upon the current scroll position. I also want it to stay centered when I scroll. As of right now it doesn't float at the center of the screen.

What javascript property do I need to use to adjust the position of the popup div as I scroll.

I've tried, but to no avail:

function showModal(id)
{
   window.onscroll = function () { document.getElementById(divID).style.top =
                                               window.pageYOffset || 
                                               document.body.scrollTop || 
                                               document.documentElement.scrollTop; };
   document.getElementById(id).style.display = "block";
   document.getElementById(id).style.top =
                 window.pageYOffset || 
                 document.body.scrollTop || 
                 document.documentElement.scrollTop; };
}

I'm using straight vanilla javascript, no jQuery.

TL;DR: I've created a modal popup but it doesn't stay centered when I scroll away from the very top of the page.

Bob
  • 43
  • 1
  • 3

2 Answers2

2

try position: fixed for your css, it won't scroll with this, also check display HTML page after loading complete

example:

<style>
#floater    {float:left; height:50%; margin-bottom:-1px;}
#top        {position: fixed; top:0; left: 0; width: 100%; height: 100%; background: #fff}
#content    {clear:both; height:540px; position:relative; height: 100%; width: 100%;}
</style>
<div id="top">
    <div id="floater"></div>
    <div id="content">
        <div style="border: 1px solid #DDD; padding: 10px; background: #BBB; width: 300px; margin: 0 auto">Popup Contents Here</div>
    </div>
</top>
  • #top element makes hides background, you can make it transparent but still unclickable.
  • #floater and #content are for vertical centering.
Community
  • 1
  • 1
aularon
  • 11,042
  • 3
  • 36
  • 41
  • the page will still scroll, but the popup div will keep fixed. – aularon Sep 02 '10 at 19:12
  • I don't want the pop up div to stay fixed. I want it to float at the center of the page. – Bob Sep 02 '10 at 19:22
  • I added an example to clarify what I mean, try with that. – aularon Sep 02 '10 at 19:59
  • You got it. Thanks a ton! My css was just garbage. I had tried fixed just as you suggested and it didn't work, like at all. Then I went back and cleaned up my code. Viola! – Bob Sep 02 '10 at 20:59
0

Modal Popup, OnClose popup event, and more!

https://github.com/reduardo7/xpopup

Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94