I've read over 10 threads/questions here but none of them works. I recently figured out how to show a modal that hides and/or disable the scrolling. Next, I figured out how to prevent my page from briefly shifting to the right for a second because of the removal of scrollbar (ugly effect). I ended up with the scrollbar still shown but disabled scrolling similar to Facebook when you open a modal there.
But, I'm facing a problem where it scrolls to the topmost part of the page automatically. I've tried a lot of things to address but to no avail.
- Of course, I disabled the default click event by e.preventDefault()
- I assigned overflow:hidden to body when opening the modal. I also did it with overflow-y:hidden to the body.
- Some say when body is set to 100%, you set it to auto when you open the modal. It doesn't work. I did it vice versa, too.
I wanted to repeat that the codes below do work. They disable the scroll and not shift my page to the right because the scrollbar stays but just disabled. I wish to get rid of the abrupt scrolling to the topmost part of the page whenever I open the modal.
UPDATE: I ADDED SNIPPET
$(document).on("click", "a", function(e) {
e.preventDefault();
$(".parentbox").show();
$("body").addClass("no-scroll");
});
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
}
html {
overflow-y: scroll;
}
.no-scroll {
overflow: hidden;
}
.parentbox
{
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.box
{
position: absolute;
background-color: #FFFFFF;
padding: 28px 18px;
text-align: center;
width: 320px;
top: 50%;
transform: translateY(-50%);
left: 0;
right: 0;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<body>
<div class="content">
<p><strong>Top section</strong></p>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div class="parentbox">
<div class="box">
This is a modal
</div>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<a href="#">Open Modal</a>
<br/><br/><br/>
</div>
</body>
</html>