- Prevent Scroll On Scrollable Elements [JS & CSS]
- 1. Cancelling scroll using JavaScript
- 2. Disabling scroll with only CSS
- 3. Preventing keyboard scroll using JavaScript
- 4. Preventing touch scroll using JavaScript
- 5. Using a npm module to disable scroll
- Related articles
- Как отключить скролл css
- How to disable scroll with CSS?
- Pre-requisites
- Overflow CSS Property
- overflow: visible
- overflow: hidden
- overflow: scroll
- overflow: auto
- overflow-x & overflow-y
- Hide Scrollbars
- Bonus: Hide but still Scroll
- Conclusion
- Sharing is caring
- EvgeniyaPronina / no scroll
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.
document.querySelector('#scrollable').addEventListener('wheel', preventScroll, passive: false>);
function preventScroll(e)
e.preventDefault();
e.stopPropagation();
return false;
>
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.
document.querySelector('.scrollable').forEach(function(item)
item.addEventListener('wheel', preventScroll);
>);
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.
.disable-scroll
overflow-y: hidden;
>
Then, with JavaScript we simply add or remove it when we want:
function disable()
document.querySelector('.scrollable').classList.add('disable-scroll');
>
function enable()
document.querySelector('.scrollable').classList.remove('disable-scroll');
>
document.querySelector('#prevent').addEventListener('click', disable);
document.querySelector('#allow').addEventListener('click', enable);
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.
document.addEventListener('keydown', preventKeyBoardScroll, false);
function preventKeyBoardScroll(e)
var keys = [32, 33, 34, 35, 37, 38, 39, 40];
if (keys.includes(e.keyCode))
e.preventDefault();
return false;
>
>
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:
var scrollable = document.querySelector('.scrollable');
scrollable.addEventListener('touchmove', disable, passive: false>);
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.
Related articles
Как отключить скролл css
Чтобы отключить скролл страницы в CSS, можно использовать свойство overflow для задания свойства hidden . Это свойство скрывает любой контент, который выходит за границы родительского элемента.
Например, если вы хотите отключить скролл на всей странице, вы можете добавить следующее правило в свой CSS файл:
Это скроет скролл на странице, но также отключит и возможность прокрутки страницы. Если вы хотите отключить скролл только для определенного элемента, вы можете применить этот стиль к этому элементу:
.container overflow: hidden; >
Здесь мы применяем свойство overflow: hidden к элементу с классом container . Это скроет все контент, который выходит за границы элемента с классом container .
Если вы хотите отключить только горизонтальный или вертикальный скролл, вы можете использовать свойства overflow-x и overflow-y . Например:
body overflow-x: hidden; /* отключает горизонтальный скролл */ overflow-y: scroll; /* включает вертикальный скролл */ >
В этом примере мы отключаем горизонтальный скролл и включаем только вертикальный скролл на странице.
How to disable scroll with CSS?
Many times you want to improve the UX of your website and hence keep all the contents on a single screen hence you don’t need a scrollbar. In this tutorial, we will learn how to do exactly disable scroll with CSS on a website.
Pre-requisites
So before we try to remove the scrollbar need to learn about an important CSS property called the overflow property.
Overflow CSS Property
CSS overflow property helps us control what happens when a certain element’s content is bigger compared to the area in which you want to put it.
When this happens, it causes the content to overflow into another pane either vertically (y-axis) or horizontally (x-axis)
Now let’s take a look at all the values the overflow property can take and how each of them work
overflow: visible
When you don’t specify anything to the overflow property this is the default value which takes and you can see your content overflow to another area let’s look at an example of how:
Code language: HTML, XML (xml)h2>Overflow: visible h2> div id="visible" class="box"> p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum repellendus sapiente ex, placeat dolor ut. p> div>
Code language: CSS (css).box height: 200px; width: 400px; border: 1px solid red; > #visible overflow: visible; >
overflow: hidden
If you use the hidden value, the overflowing part of the content will be cut off. It will be invisible.
We don’t have to worry about the space taken up by the overflow part. Once the content has been truncated, it is no longer in the area where it had overflowed.
Code language: HTML, XML (xml)h2>Overflow: hidden h2> div id="hidden" class="box"> p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum repellendus sapiente ex, placeat dolor ut. p> div>
Code language: CSS (css).box height: 200px; width: 400px; border: 1px solid red; > #hidden overflow: hidden; >
overflow: scroll
Just like the hidden value the scroll value also cuts the content out. But it provides a scrollbar so we can scroll and see the cropped part of the content.
Let’s look at an example of how:
Code language: HTML, XML (xml)h2>Overflow: scroll h2> div id="scroll" class="box"> p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum repellendus sapiente ex, placeat dolor ut. p> div>
Code language: CSS (css).box height: 200px; width: 400px; border: 1px solid red; > #scroll overflow: scroll; >
overflow: auto
When you use the auto value for the overflow property, the scroll bar is added only in the direction in which the overflow happens.
If no overflow happens in any direction, no scrollbar will be added.
Code language: HTML, XML (xml)h2>Overflow: auto h2> div id="auto" class="box"> p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum repellendus sapiente ex, placeat dolor ut. p> div>
Code language: CSS (css).box height: 200px; width: 400px; border: 1px solid red; > #auto overflow: auto; >
overflow-x & overflow-y
Now if you want to check for overflow in a specific direction that is the x-axis and y-axis you can use the overflow-x and overflow-y properties.
- overflow-y: CSS property to specify what happens when content overflows vertically i.e from top to bottom
- overflow-x: CSS property to specify what happens when content overflows horizontally i.e from left to right.
The same four values of visible scroll and auto can be used with these properties as well.
Hide Scrollbars
To completely hide the scrollbars from your page, as we saw earlier we can use the overflow: hidden property.
It hides both the vertical and horizontal scroll bars.
Code language: CSS (css)body overflow: hidden; >
If you want to hide only the vertical scrollbars or the horizontal scrollbars you can use the overflow-y and overflow-x properties as required.
Code language: CSS (css)body overflow-x: hidden; /*hides horizontal scrollbar*/ overflow-y: hidden; /*hides vertical scrollbar*/ >
Bonus: Hide but still Scroll
Now here’s a bonus tip if you want to just hide the scroll bars but not completely get rid of the functionality that the scrollbars provide you can use the following code on your website:
Code language: HTML, XML (xml)h2>Bonus: Scroll but hide Scrollbars h2> div class="bonusBox"> p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum repellendus sapiente ex, placeat dolor ut! . p> div>
Code language: CSS (css)/* Hide scrollbar for IE, Edge and Firefox */ .bonusBox height: 200px; width: 400px; border: 1px solid green; overflow-y: scroll; -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ > /* Hide scrollbar for Chrome, Safari and Opera */ .bonusBox::-webkit-scrollbar display: none; >
Conclusion
In this tutorial, we learn how we can control the overflow of content on a website, and how we can disable scroll with CSS we also got a bonus tip on implementing the scroll functionality but also hiding the scroll bars.
We used codedamn playgrounds in this tutorial and how can try it out yourself by forking this playground.
I hope you liked reading this article! ?
P.S: I have won many hackathons and worked on many projects. You can connect with me on LinkedIn to know about hackathon ideas, internship experiences, and Development tips.
Sharing is caring
Did you like what Subhanu Sankar Roy wrote? Thank them for their work by sharing it on social media.
EvgeniyaPronina / no scroll
Убрать полосы прокрутки полосу прокрутки, и запретить скролл(scroll) на сайте при помощи css или js когда нам она не нужна, например при отображении того же попап окна (popup window) или любого другого всплывающего элемента на странице (рекламы).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
//Запретить скролл: |
$(«html,body»).css(«overflow»,»hidden»); |
//или только вертикальный скролл: |
$(«body»).css(«overflow-y»,»hidden»); |
//и на css: |
position:fixed;overflow:hidden |
//Запретить scroll на чистом JS можно так: |
document.body.style.overflow = ‘hidden’; |
//Убрать скроллинг на IPAD можно так: |
document.body.addEventListener(‘touchmove’,function(event),false); |
//на jQuery: |
$(document).bind(‘touchmove’, false); |
//P.S: Данный способ не работает на мобильных устройства, так как там используется точпад, по этому необходимо для body применять свойство position:fixed; пример: |
создаем сам класс |
.fixed |
position:fixed; /*позицианируем чтобы исчез скролл*/ |
width:100%; /*что бы верстка не складывалась по ширине*/ |
> |
//Применяем когда нам это необходимо |
$(«body»).addClass(«fixed»); |
//и убираем его когда нужно сновa включить прокрутку |
$(«body»).removeClass(«fixed»); |