Last Updated: February 25, 2016
·
494
· slue

Disappearing scrollbars on popups

When using lightbox or any other popup on a website, a typical problem is to handle the scrollbars from the main page.

Adding overflow: hidden; on the body when opening the popup and removing it on closing, would just hide the scrollbar and disable scrolling. Thats fine on a typical mac, where you do not have any visible scrollbars, unless you are, in fact, scrolling.

But when you plug in a mouse or use any other system, you're getting in trouble, because now, the scrollbars are visible all the time. Simple adding overflow: hidden; does not work anymore, because that underlying page of the popup would jump, because the scrollbar disappears.

The solution is found on stackoverflow

First, you need a css-class

html.noscroll {
    position: fixed; 
    overflow-y: scroll;
    width: 100%;
}

Then run this code when opening the popup

if ($(document).height() > $(window).height()) {
     var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
     $('html').addClass('noscroll').css('top',-scrollTop);         
}

Last but not least, you need this snippet to run on closing the popup

var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll');
$('html,body').scrollTop(-scrollTop);

thats it.