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;.

3
  • 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. Commented Sep 21, 2011 at 16:11
  • Can you explain the reason you don't want to use overflow-x:hidden? Commented Sep 21, 2011 at 17:05
  • 1
    Possibly because iOS has a tendency to ignore it in many cases. Commented Oct 30, 2013 at 0:33

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the note on frustrated users, count me in that group :)
I usually set overflow-x: hidden. But usually that doesn't prevent browsers from scrolling target horizontally with OSX touchpad.
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.

2 Comments

@Reuben Use scrollLeft instead of scrollTop then.
I would say remove this.scrollTop = 0; and this is definitely the answer!
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.