Как отключить прокрутку страницы css
Перейти к содержимому

Как отключить прокрутку страницы css

  • автор:

Запрет прокрутки при открытии модального окна

Бывало у вас такое? Открываете модальное окно, прокручиваете, а после закрытия оказываетесь на странице в позиции, отличающейся от той, с которой его открывали.

Подобное может происходить из-за того, что модальные окна являются такими же элементами страницы, как и любые другие. Они могут располагаться в фиксированной позиции, не препятствуя работе с остальным содержимым документа.

Порой это не становится проблемой. Например, когда высота содержимого страницы не превышает высоту области видимости экрана пользователя. Однако, в остальных случаях мы неизбежно сталкиваемся с этим. Хорошей новостью является то, что мы можем предотвратить появление скролла с помощью трюка с использованием CSS и JavaScript.

Давайте начнём с чего-нибудь простого

При открытии модального окна можно просто устанавливать элемент body по высоте равным области видимости (viewport) и скрывать вертикальную прокрутку:

Решение имеет право на существование, но если перед открытием модального окна мы прокрутим элемент body , получим небольшую перерисовку содержимого. Ширина области видимости расширяется приблизительно на 15px, что соответствует ширине полосы прокрутки.

Давайте немного отрегулируем правый padding для body , чтобы избежать этого.

Обратите внимание – чтобы это сработало, модальное окно должно быть по высоте меньше области видимости. Иначе полоса прокрутки будет нужна.

Отлично. А что насчёт мобильных?

Это решение отлично работает как на десктопах, так и на мобильных Android-устройствах. Однако, Safari для iOS требует немного больше внимания, поскольку body всё ещё может прокручиваться, когда модальное окно открыто.

Как альтернатива, мы можем задать для body фиксированное позиционирование.

Работает. Теперь body не будет реагировать на свайпы по экрану. Тем не менее, небольшая проблема всё же остаётся. Если кнопка, открывающая модальное окно, находится внизу страницы и чтобы её увидеть, нужно прокручивать страницу, при нажатии на эту кнопку и открытии модального окна, будет происходить автоматическая прокрутка страницы вверх, что может дезориентировать так же, как и фоновая прокрутка body , от которой мы пытаемся избавиться.

Вот поэтому нам не обойтись без JavaScript

Можем использовать JavaScript, чтобы избежать всплытия события прикосновения к экрану. Все мы знаем, что при открытии модального окна, у него должен быть фоновый слой. К сожалению, в iOS метод stopPropagation() с событиями прикосновения работает немного неуклюже. Но у preventDefault() таких проблем нет. Это значит, что мы должны добавить обработчики событий к каждому DOM-элементу внутри модального окна, а не только к слою подложки или самому модальному окну. Хорошая новость в том, что много JavaScript-библиотек могут делать это, включая старый добрый jQuery.

Ах да, и ещё кое-что. Что если нам нужна прокрутка внутри модального окна? Нам всё ещё нужно вызвать реакцию на событие свайпа, но при достижении верха или низа модального окна, нам всё ещё нужно предотвращать всплытие. Кажется очень сложным (?? так что мы ещё не полностью выкарабкались).

Давайте улучшим фиксированный body

Вот с чем мы работали:

С помощью JavaScript можно вычислить положение прокрутки страницы, и добавлять это значение в CSS. Благодаря этому body не будет прокручиваться обратно в начальную позицию.

Данное решение работает, но после закрытия окна всё ещё происходит небольшой сдвиг. А именно, похоже, когда модальное окно открыто и для body задано фиксированное позиционирование, страница уже теряет положение прокрутки. Следовательно, нам нужно восстановить положение. Давайте изменим JavaScript, чтобы учитывать этот момент.

Вот и всё. Теперь body не будет прокручиваться при открытом модальном окне, а положение прокрутки сохраняется и при открытии и при закрытии модального окна.

How to Hide the Scrollbar in CSS

Jamie Juviler

Designing a website exactly how you want often requires cutting out the excess — some whitespace here, an underline there, or, in today’s case, the scrollbar.

Two people using a computer to hide the scrollbar using CSS

Whether for design or functionality reasons, it’s easy to hide the scrollbar on a page or page element with a bit of CSS. There are multiple ways to do this — hiding the scrollbar while allowing scrolling, hiding it while disabling scrolling, and keeping the scrollbar hidden only until it’s needed — some of which will work better based on your case.

To meet your design needs, this guide will cover all of these methods. Let’s get started.

Prevent Scroll On Scrollable Elements [JS & CSS]

If you ever need to temporally disable scrolling on a specific scrollable element, then you will need to use JavaScript or CSS for it. Depending on your use case, you can choose between JavaScript and CSS solutions. Although in general terms the CSS solution is the most adopted one, JavaScript offers you a bit more of control and flexibility and allows you to decide how exactly you want to stop the scrolling.

1. Cancelling scroll using JavaScript

One of the options is to listen to the wheel event on the element you want to prevent the scrolling and then prevent the default behavior as well as stopping the propagation and returning a false value.

Something as simple as this, where #scrollable would be the ID of our scrollable element.

Notice as well that we are using the option on the event listener. This is actually because we have to tell browsers that, eventually, we might call preventDefault and cancel the default behavior. This way the browser is aware of it and can decide how to treat the event. You can read more about it on the docs.

If you need to provide support for IE 11 you might need to add a fallback for the passive event param as it is not supported check if the passive event is supported.

Now, what if we want to enable or disable this dynamically? Here's an example with a couple of buttons, one to disable the scroll and another one to enable it:

If you want to apply it to multiple elements, it is as easy as iterating over them and applying them to the same function.

Now, take a look at the CSS way because the JS way can get a bit more complicated if we take into account keyboard and touch scrolling.

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

It is clearly the easiest solution if you want to disable scroll no matter what triggers it (mouse, keyboard, or touch), but at the same time, it won't give you the flexibility of choosing what to disable and what not.

There's a couple of differences with the previous way. They can be good for you, or not, depending on your use case:

It will also disable the keyboard scrolling too. So, you won't be able to move up or down by using the keyboard arrows and space bar, etc.

It will not allow you to scroll up/down by selecting text.

It will disable touch scroll too.

It might also prevent scrolling using "the third button" of the mouse, which is pressing the mousewheel while dragging the mouse. (If anyone can verify this for me that'd be great, as I don't have a mouse to test it at the moment 🙂 )

So, how do we do it? We create a class that we will toggle whenever we need it and that all it does is preventing the scroll on the element we apply it.

Then, with JavaScript we simply add or remove it when we want:

Here's a working example:

3. Preventing keyboard scroll using JavaScript

If you decide to go for the JS solution, then you might also want to disable scroll through the keyboard.

In this case, we simply have to listen to the keydown event and prevent the default behavior when we detect they are pressing any key that can trigger a scroll movement, such as the keyboard arrows, spacebar, shift+space bar, pageup, pagedown etc.

And here's the example:

4. Preventing touch scroll using JavaScript

And of course, we can't forget about the touch scroll. The CSS solution seems to make things like this much easier for us, but if we need total control over what we allow users to do and what not, then probably the JavaScript version is the way to go.

Regarding touch events, this is pretty similar to canceling the scroll for the wheel event.

We simply have to add the exact same function on a touchmove event listener:

5. Using a npm module to disable scroll

You will also find there are a few components and modules out there that give you this feature out of the box.

Some only apply to the whole document while others allow you to be applied to specific scrollable elements.

Here's a few I found:

Related articles

Ezoic

report this ad

How to disable scroll without hiding it?

I’m trying to disable the html/body scrollbar of the parent while I’m using a lightbox. The main word here is disable. I do not want to hide it with overflow: hidden; .

The reason for this is that overflow: hidden makes the site jump and take up the area where the scroll was.

I want to know if its possible to disable a scrollbar while still showing it.

I_love_vegetables's user avatar

Dejan.S's user avatar

25 Answers 25

If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set

you should still see the right scrollbar but the content is not scrollable. When you close the overlay just revert these properties with

I just proposed this way only because you wouldn’t need to change any scroll event

What if I already scrolled the page?

if you get the document.documentElement.scrollTop property via javascript just before the layer opening, you could dynamically assign that value as top property of the body element: with this approach the page will keep its current scroll position, no matter if you’re on top or if you have already scrolled.

Css

JS

Four little additions to the accepted solution:

  1. Apply ‘noscroll’ to html instead of to body to prevent double scroll bars in IE
  2. To check if there’s actually a scroll bar before adding the ‘noscroll’ class. Otherwise, the site will also jump pushed by the new non-scrolling scroll bar.
  3. To keep any possible scrollTop so the entire page doesn’t go back to the top (like Fabrizio’s update, but you need to grab the value before adding the ‘noscroll’ class)
  4. Not all browsers handle scrollTop the same way as documented at http://help.dottoro.com/ljnvjiow.php

Complete solution that seems to work for most browsers:

CSS

Disable scroll

Enable scroll

Thanks to Fabrizio and Dejan for putting me on the right track and to Brodingo for the solution to the double scroll bar

isherwood's user avatar

With jQuery inluded:

disable

enable

usage

ceed's user avatar

With the help of answer from fcalderan I was able to form a solution. I leave my solution here as it brings clarity to how to use it, and adds a very crucial detail, width: 100%;

I add this class

this worked for me and I was using Fancyapp.

Dejan.S's user avatar

This worked really well for me.

just wrap those two lines of code with whatever decides when you are going to lock scrolling.

You cannot disable the scroll event, but you can disable the related actions that lead to a scroll, like mousewheel and touchmove:

tocqueville's user avatar

You can hide the body’s scrollbar with overflow: hidden and set a margin at the same time so that the content doesn’t jump:

And then you can add a disabled scrollbar to the page to fill in the gap:

I did exactly this for my own lightbox implementation. Seems to be working well so far.

Here is a working demo. This is how you can do this with pure JavaScript:

And this is the CSS:

We use position: fixed on body to prevent it from being scrollable and we use overflow-y to show the scrollbar. We also need to set width because of how position: fixed works.

We keep track of the scroll position and update it when disabling scroll so that we can position body appropriately using top when scroll is disabled and restore the scroll position when it is enabled. Otherwise body will keep jumping to the top when disabling or enabling scroll.

When enabling scroll we remove the top style from body . This prevents it from breaking your layout if you have a different position than static on body .

If you are using scroll-behavior: smooth on html , you also need to modify the enableScroll function like this:

We need to temporarily set scroll-behavior to auto so that there are no jumps.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *