David King

full stack developer

All Blog Articles

Prev « Anyone up for a 24-hour hack? Next » My Chrome Extension > Tweakr

CSS / jQuery how to toggle scrollbars for a lightbox

13 Jan 2012

A few months back I was reverse engineering the Facebook photo overlay and noticed that they have employed a very neat trick with-regard-to scrolling; when the photo "popup" is active, the body underneath does not scroll.

It's a very subtle UI feature but fixes a thoroughly annoying "bug" for many people. Normally when you view scrollable content in a "lightbox" you would scroll to the bottom of the lightbox and then the PAGE UNDERNEATH STARTS TO SCROLL too, what a buggerlug.

The trick is to simply prevent the body from scrolling; using a little CSS we can set the body overflow to be hidden (removes the scrollbars) and put a margin on the html to stop the page moving about (body would expand into the space the scrollbar was otherwise):

/* Don't scroll */
html.noscrollbar {margin-right: 15px;}
html.noscrollbar body {overflow: hidden;}

Or if (like me) you'd prefer to leave your CSS be and implement it with jQuery:

// Remove the scroll
$('html').css('margin-right', '');
$('body').css('overflow', '');
// Return the scroll to normal $('html').css('margin-right', '15px'); $('body').css('overflow', 'hidden');

I use the jQuery method in a hush-hush project that I've been working on for the past few months (and for the foreseeable future*) here's a not-too-revealing screenie

A screenshot

* a blog post in itself

Prev « Anyone up for a 24-hour hack? Next » My Chrome Extension > Tweakr