tags:

views:

83

answers:

1

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.

+1  A: 

try position: fixed for your css, it won't scroll with this, also check http://stackoverflow.com/questions/3629762/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.
aularon
I want to be able to scroll.
Bob
the page will still scroll, but the popup div will keep fixed.
aularon
I don't want the pop up div to stay fixed. I want it to float at the center of the page.
Bob
I added an example to clarify what I mean, try with that.
aularon
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
You are welcome : )
aularon