1

I have a popup box that opens/show when clicking or hovering over a href anchor. It shows in the center of the page. When you are scrolling down or on mobile it doesn't work anymore because the popup shows at the "top" (centered), but not the center of the current view.

I tried with css

.modal-box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
}

and javascript

$(window).resize(function() {
    $(".modal-box").css({
        top: ($(window).height() - $(".modal-box").outerHeight()) / 2,
        left: ($(window).width() - $(".modal-box").outerWidth()) / 2
    });
});
 
$(window).resize();

Both do the effect mentioned above (centering) but not when scrolled a bit further... Is there a way to fix that? Or would it better to use some plugin (lightbox or whatever) to do this?

sigug
  • 1,159
  • 1
  • 11
  • 17

1 Answers1

3

Your css (as well as js) is correct. Choose the CSS solution as it is more optimized. Is there some css at any of the parent of the .modal-box which makes it to scroll?

your code works correct here: https://jsfiddle.net/w1k5aLe7/

Sudipto Roy
  • 948
  • 8
  • 15
  • Hm, thanks, but somehow not on mobile. E.g.http://uf.framefaktur.de/en/about/ The first two popups work, but the last ones don't show at all? Also, what would be the best way to prevent constant "open/close" when moving mouse over anchor, now it flixers? – sigug Jul 25 '20 at 10:17
  • 1
    Using mouse events for mobile will for sure introduce bugs. Switch to straight forward `click` event. And use the `.toggle()` function instead of `.hide()` and `.show()`. – Sudipto Roy Jul 25 '20 at 10:31
  • 1
    i've made some changes to the dom and have achieved the same functionality through css: https://jsfiddle.net/wcvtesor/ This should work for mobile aswell. – Sudipto Roy Jul 25 '20 at 10:44
  • Thank you! Do you know if that (great) solution would be possible for opening that box and dimming all other inactive ones while that box is open? I opened another question: https://stackoverflow.com/questions/63087636/toogle-class-of-other-divs-except-the-one-clicked – sigug Jul 25 '20 at 11:19