Justin808
Justin808

Reputation: 21522

CSS - Prevent scrolling but leave the scrollbar

I'm using overflow:hidden to prevent the body from scrolling when an overlay is shown. The problem is this removes the scrollbar so the whole page shifts a bit to the right. It shifts again when the overlay is removes and the overflow is set back to auto.

Is there a way to get around this? I would like to freeze the document from scrolling but would like to prevent the page from jumping around.

jsfiddle

Upvotes: 1

Views: 1188

Answers (2)

No Results Found
No Results Found

Reputation: 102864

You can add this:

html {
     overflow-y:scroll;
}

The body element will hide overflow (as you already have it), and the html element will just display an empty scroll bar. This works since you happen to have html and body set at height:100%.

Demo: http://jsfiddle.net/BCX64/3/

Alternatively, you can prevent scrolling like this when you show the overlay:

// Find current scroll positions
var top = $(window).scrollTop();
var left = $(window).scrollLeft()

$(window).scroll(function(){
    // Force scroll back to original positions
    $(this).scrollTop(top).scrollLeft(left); 
});

Then unbind the event when you hide the overlay:

$(window).unbind('scroll');

You don't need the noscroll class in this case.

Demo: http://jsfiddle.net/BCX64/6/

Upvotes: 1

Juni Brosas
Juni Brosas

Reputation: 1496

What if you create a fake scrolling bar and place it in the right side.. you can customize the design too.

Upvotes: 0

Related Questions