6

I've got a few divs that hold information that you can scroll through. But when you hit the top or bottom it changes to the browsers scroll which scrolls the entire page.

I'd like to disable outside scrolling while the mouse is inside of this particular div (there's three of this type of div).

An example of what I'm trying to acheive is youtubes playlist selector.

Here's an example at youtube Hover your mouse inside the popular uploads part and trying scrolling all the way up and down.

EDIT: just tried to use the link in another browser and the video selection part doesn't seem to show up, but it's the "add to playlist" part that enables it.

Does anybody know of a way to do this?

Trevor Wood
  • 2,347
  • 5
  • 31
  • 56

2 Answers2

4

Here's a FIDDLE

<div>
  ... some content ...
</div>

div {
  height: 400px;
  overflow: scroll;
}

$('div').on('mousewheel DOMMouseScroll', function(e) {
  var scrollTo = null;

  if(e.type === 'mousewheel') {
     scrollTo = (e.originalEvent.wheelDelta * -1);
  }
  else if(e.type === 'DOMMouseScroll') {
     scrollTo = 40 * e.originalEvent.detail;
  }

  if(scrollTo) {
     e.preventDefault();
     $(this).scrollTop(scrollTo + $(this).scrollTop());
  }
});
Milan and Friends
  • 5,560
  • 1
  • 20
  • 28
  • 1
    The fiddle doesn't work for me. The text and the page both scroll at the same time. Is it because I'm using a Mac touchpad instead of a mouse? Is there a touchpad version of this solution? – Mcbeese Apr 04 '18 at 07:00
2

Untested, but might be the answer:

$( "div" ).scroll(function( event ) {
    event.stopPropagation();//Do not bubble up the DOM, do not scroll document.
});

stopPropagation() is used to prevent the event of bubbling up the DOM. This way other elements are not notified of this event.

Read more: http://api.jquery.com/event.stoppropagation/

Salketer
  • 14,263
  • 2
  • 30
  • 58