8

Does anyone know if there is a way to disable the horizontal scrollbar using JavaScript?

I don't want to use overflow-x: hidden;.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Jay
  • 721
  • 3
  • 9
  • 15
  • 3
    Really, the easiest way would be to apply the overflow-x style when you want to hide the scrollbar and then remove it when you want it to show. – n8wrl Sep 21 '11 at 16:11
  • Can you explain the reason you don't want to use `overflow-x:hidden`? – Sparky Sep 21 '11 at 17:05
  • 1
    Possibly because iOS has a tendency to ignore it in many cases. – El Yobo Oct 30 '13 at 00:33

3 Answers3

10

Without using the perfectly workable overflow-x CSS property, you could resize the content to not require a scroll bar, through javascript or through HTML/CSS design.

You could also do this:

window.onscroll = function () {
 window.scrollTo(0,0);
}

... which will detect any scrolling and automatically return the scroll to the top/left. It bears mentioning that doing something like this is sure to frustrate your users.

You're best served by creating an environment where unwanted UI elements are not present at all (through the CSS, through design). The approach mentioned above shows unnecessary UI elements (scroll bars) and then causes them to not work in a way that the user expects (scroll the page). You've "broken a contract" with the user - how can they trust that the rest of your web site or application will do expected things when the user makes a familiar action?

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
2

A way to prevent elements from scrolling down in jQuery:

$(element).scroll(function () {
    this.scrollTop = 0;
    this.scrollLeft = 0;
});

Well, this does not actually prevent the scrolling, but it "scrolls back" to the top-left corner of an element, similar to Chris' solution which was created for the window instead of single elements. Remove the scrollTop or scrollLeft lines to suit your needs.

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
0

A dirty trick would be overlapping the scrollbars: http://jsfiddle.net/dJqgf/.

var overlap = $('<div id=b>');

$("#a").wrap($('<div>'));

$("#a").parent().append(overlap);

with:

#a {
    width: 100px;
    height: 200px;
    overflow-x: scroll;
}

#b {
    position: relative;
    left: 0;
    bottom: 20px;
    width: 100%;
    height: 20px;
    background-color: white;
}
pimvdb
  • 151,816
  • 78
  • 307
  • 352