Reputation: 3183
I'm trying to disable horizontal scroll on a website; but allowing vertical scrolling.
I have a script which works like a slider by sliding the 'body' of the page left and revealing more contents. However this creates extra empty space on the right.
I need to disable horizontal scrolling so users don't see this empty space. I tried the following script but it disables both horizontal and vertical scrolling:
window.onscroll = function () {
window.scrollTo(0,0);
}
I have tried overflow-x: hidden
but that doesn't work when the body's width is dynamic and not static.
Is there a way to modify the above script to disable the horizontal scrolling and keep vertical scrolling?
Upvotes: 17
Views: 42194
Reputation: 399
You could also jQuery's "on", and check for the deltaX.
$("body").on("wheel", function(e) {
var deltaX = e.originalEvent.deltaX;
if (deltaX !== 100 && deltaX !== -100) {
// ...do something
}
return false;
});
Upvotes: 2
Reputation: 49
Here is what I did to solve my problem.
window.onscroll = function () {
window.scrollTo(0,window.scrollY);
};
Hope this helps.
Upvotes: 4
Reputation: 8559
CSS:
body {
width: 100vw;
height: 100vh;
overflow: hidden auto;
}
The 100vw/vh
means 100% of the view-port (=window inner) width/height.
The hidden auto
means never show scroll on x and show scroll on y when necessary.
Upvotes: 0
Reputation: 10701
Without JQuery:
window.onscroll = function () {
window.scrollLeft = 0;
}
Upvotes: 5
Reputation: 41
use overflow-x:hidden on your wrapper element
overflow-x:hidden;
Upvotes: 4
Reputation: 7862
You were close to get it. You need to get the document
—or window
— and bind the scroll: then you can check if the scrollLeft
is updated to more than 0 and set the scrollLeft
to 0.
The next code works well:
$(function() {
var $body = $(document);
$body.bind('scroll', function() {
// "Disable" the horizontal scroll.
if ($body.scrollLeft() !== 0) {
$body.scrollLeft(0);
}
});
});
If you want to disable horizontal scroll for an element (like div, for instance) you only need to replace $(document)
by $("#yourElementID")
JSFiddle: https://jsfiddle.net/tomloprod/zx1bvdf5/
NOTE:
The above script will prevent you scroll horizontally and, in addition, you can use the next CSS style:
overflow-x:hidden;
to hide the horizontal scroll.And will be like if there were no horizontal scrolling.
Upvotes: 24
Reputation: 59232
This should work (CSS):
html, body {
max-width: 100% !important;
overflow-x: hidden !important;
}
Upvotes: 16