oneday
oneday

Reputation: 1629

How to stop body scroll but keep the scrollbar?

I'm trying to adjust Bootstrap carousel to work on mousewheel. So far the jQuery looks like this:

$('#thumbnailCarousel').bind('mousewheel', function(e){
  $(this).carousel('next');
});
$('#thumbnailCarousel').mouseover(function() {
  $('body').css('overflow-y','hidden');
});
$('#thumbnailCarousel').mouseleave(function() {
  $('body').css('overflow-y','scroll');
});

The first part makes the gallery scrollable with mousewheel. The problem was that the body was scrolling at the same time, so I gave it "overflow-y: hidden" on mouseover.

It's almost what I want now, except that with overflow:hidden the scrollbar obviously dissapears and the layout jumps to the right. It's really ugly, so is there any way I can prevent the body from scrolling while keeping the scrollbar in place?

Upvotes: 0

Views: 616

Answers (2)

drew_w
drew_w

Reputation: 10430

I'm not sure if this is the best solution but you could easily add padding to the body exactly the same width of the scroll bar while it is hidden and that would eliminate the sliding. The following code is an example:

$('#thumbnailCarousel').mouseover(function() {
  $('body').css('overflow-y','hidden');
  $('body').css('padding-right', '17px');
});
$('#thumbnailCarousel').mouseleave(function() {
  $('body').css('overflow-y','scroll'),
  $('body').css('padding-right', '0px');
});

See This Working: http://jsfiddle.net/2gkn9/1/

...with dynamic scroll bar width: http://jsfiddle.net/2gkn9/2/

NOTE - This of course isn't complete because the width of the scroll bar is going to change between browsers and across devices. So, you'll want to make sure you get the width of the scroll bar dynamically. The first solution I found for that was here: How can I get the browser's scrollbar sizes?

Hope that helps!

Upvotes: 1

graphicdivine
graphicdivine

Reputation: 11211

Try:

$('#thumbnailCarousel').bind('mousewheel', function(e){
  $(this).carousel('next');
  e.stopImmediatePropagation();
  e.stopPropagation();
  e.preventDefault();
});

Upvotes: 1

Related Questions