Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable a browser or element scrollbar, but still allow scrolling with wheel or arrow keys?

I want to hide any scrollbars from my div elements and my whole body, but still let the user scroll with the mouse wheel or arrow keys. How can this be achieved with raw JavaScript or jQuery? Any ideas?

like image 693
Shizoman Avatar asked Aug 25 '09 07:08

Shizoman


People also ask

How do you stop an element from scrolling?

Disabling scroll with only CSS. There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.

How do I disable scrolling on my website?

To hide the horizontal scrollbar and prevent horizontal scrolling, use overflow-x: hidden: HTML. CSS.


1 Answers

Like the previous answers, you would use overflow:hidden to disable the scrollbars on the body/div.

Then you'd bind the mousewheel event to a function that would change the scrollTop of the div to emulate scrolling.

For arrow keys, you would bind the keydown event to recognize an arrow key, and then change scrollTop and scrollLeft of the div as appropriate to emulate scrolling. (Note: you use keydown instead of keypress since IE doesn't recognize keypress for arrow keys.)
Edit: I couldn't get FF/Chrome to recognize keydown on a div, but it works in IE8. Depending on what you needed this for, you can set a keydown listener on the document to scroll the div. (Check out the keyCode reference as an example.)

For example, scrolling with the mouse wheel (using jQuery and a mousewheel plugin):

<div id="example" style="width:300px;height:200px;overflow:hidden"> insert enough text to overflow div here </div>  <script> $("#example").bind("mousewheel",function(ev, delta) {     var scrollTop = $(this).scrollTop();     $(this).scrollTop(scrollTop-Math.round(delta)); }); </script> 

(This is a quick mockup, you'd have to adjust the numbers since for me, this scrolls a bit slowly.)

keyCode reference
mousewheel plugin
keydown, keypress @ quirksmode

Update 12/19/2012:

The updated location of the mousewheel plugin is at: https://github.com/brandonaaron/jquery-mousewheel

like image 109
Grace Avatar answered Oct 07 '22 23:10

Grace