Javascript modal popup

I am trying to create a simple modal popup. I have CSS, and Javascript is basically done. I am at the point where I click the button on the page button and a popup appears, but it appears at the top of the page. It seems that it would be nice if you scroll to the very top of the page.

However, I want the modal popup to appear in the center based on the current scroll position. I also want it to stay centered when I scroll. At the moment, he does not swim in the center of the screen.

What javascript property should be used to adjust the position of the pop-up div when scrolling.

I 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 use direct vanilla javascript, without jQuery.

TL DR: I created a modal popup, but it does not stay centered when I scroll away from the very top of the page.

+4
source share
2 answers

try position: fixed for your css, it will not scroll with this, also check the HTML page display after full loading

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> 
  • Element
  • #top makes a hidden background, you can make it transparent, but nonetheless unattractive.
  • #floater and #content are for vertical centering .
+2
source

Modal popup, OnClose popup event and more!

https://github.com/reduardo7/xpopup

0
source

All Articles