I have a sidebar for mobile and it takes up 300px from the left of the screen when it shows. I check if it shows with a variable called isOpen.
<Navbar isOpen={isOpen} setIsOpen={setIsOpen} />
<div className={isOpen ? "content behind" : "content"}>
//content
</div>
How do I disable clicking and scrolling for the div under the navbar when the sidebar is active?
.content.behind{
pointer-events: none;
}
I tried using this but scrolling is still possible.
.content.behind{
overflow: hidden;
}
I tried this too, but when the sidebar is shown, the top of the content section is shown because the overflows are hidden.
I also found this custom hook on github. useScrollBlock It worked, but when I use it, scrollable is disabled for the whole body. It should be possible to scroll for the sidebar.
2
Answers
I’m assuming
.contant
is your scrollable element (rather then the whole body). In that case, using bothpointer-events: none
andoverflow: hidden
seems to work just fine in the example below.You can scroll down, open the sidebar, and the list’s scroll position doesn’t change. However, you’ll notice the list moves horizontally when the scrollbar is hidden (at least on Windows, where the scrollbar is not an overlay like in macOS/iOS):
In any case, maybe your problem is device-specific, or it depends on the overall HTML structure you have. You could instead just add an overlay over
#content
, which will prevent users from scrolling it or interacting with its content:In order to prevent any interaction with the main content of the page what is usually done is creating a div that is placed on top of the content (but below the modal/sidebar):
Then in the CSS define it with a
z-index
that is greater than everything in the main content but lower than the one used in the modal (my modal hasz-index: 1000
):And for hiding the scrollbars, it depends on the rest of your page design (which you haven’t shared), but the hiding of the
overflow
is usually needed at thebody
element. It can be done via CSS class, but instead I did it via useEffect:You can a working example in the snippet below: