Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable horizontal scroll; but allow vertical scroll

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.

Question:

Is there a way to modify the above script to disable the horizontal scrolling and keep vertical scrolling?

like image 879
user2028856 Avatar asked Mar 27 '14 04:03

user2028856


People also ask

How do I hide horizontal scrollbar but still scroll?

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

How do I turn off horizontal scroll wheel?

Open Settings > devices > mouse & touchpad > Turn the Scroll inactive windows when I hover over them option on. Was this reply helpful? I fixed it myself. I have stopped using the edge browser.

How can I hide scrollbar in iframe but still scroll?

1. Set the overflow of the parent div as hidden. 2. Set the overflow of the child div to auto and the width 200% (or anything more than 100%, or more than the width of the parent - so that the scrollbar gets hidden).


4 Answers

You were close to get it. You need to get the documentor 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.

like image 99
tomloprod Avatar answered Sep 19 '22 14:09

tomloprod


This should work (CSS):

html, body {
    max-width: 100% !important;
    overflow-x: hidden !important;
}
like image 33
Amit Joki Avatar answered Sep 19 '22 14:09

Amit Joki


use overflow-x:hidden on your wrapper element

overflow-x:hidden;

like image 26
Stanley Tso Avatar answered Sep 16 '22 14:09

Stanley Tso


Without JQuery:

window.onscroll = function () {
  window.scrollLeft = 0;
}
like image 41
Mikaël Mayer Avatar answered Sep 19 '22 14:09

Mikaël Mayer