I have a modal dialog to be opened. When the modal window is opened i want to disable background scroll. So i have added overflow:hidden
to the body
tag when the dialog is opened. By doing this scroll bar comes and goes for the body
tag, Which in result causing some jerk to my UI. I understand this jerk will happen because of the reserved space used by the scroll bar. Is there is any way to avoid the jerk and also to disable the background scroll when the dialog opened and closed.
Please find the code attached below
var launch = document.getElementById('btn');
var dialog = document.getElementById('dialog');
var close = document.getElementById('close');
var body = document.querySelector('body');
launch.onclick = openModal;
close.onclick = closeModal;
function openModal(){
dialog.style.display = "block";
body.style.overflow = "hidden";
}
function closeModal(){
dialog.style.display = "none";
body.style.overflow = "auto";
}
body{
margin:0;
}
.overall{
height:1000px;
width:100%;
position:relative;
text-align:right;
padding: 0;
cursor:pointer;
}
.modal{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
background:#aaa;
border:1px solid #fdfdfd;
height:200px;
width:400px;
}
span{
text-align: right;
cursor: pointer;
width: 100%;
display: block;
text-align:right;
}
<div class="overall" id="btn">
click to launch modal
</div>
<div class="modal" id="dialog" style="display:none">
<span id="close"> close</span>
</div>
Closely note click to launch text
it will have a jerk due to the above mentioned issue
Please refer the working fiddle here
You could temporarily add a margin-right
that's the width of the scrollbar. If you have lots of styling and background colors going on, it might not be sufficient. But for simple layouts it works fine.
var launch = document.getElementById('btn');
var dialog = document.getElementById('dialog');
var close = document.getElementById('close');
var body = document.querySelector('body');
launch.onclick = openModal;
close.onclick = closeModal;
function openModal(){
var widthBefore = body.offsetWidth;
dialog.style.display = "block";
body.style.overflow = "hidden";
body.style.marginRight = body.offsetWidth - widthBefore + "px";
}
function closeModal(){
dialog.style.display = "none";
body.style.overflow = "auto";
body.style.marginRight = "";
}
body{
margin:0;
}
.overall{
height:1000px;
width:100%;
position:relative;
text-align:right;
padding: 0;
cursor:pointer;
}
.modal{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
background:#aaa;
border:1px solid #fdfdfd;
height:200px;
width:400px;
}
span{
text-align: right;
cursor: pointer;
width: 100%;
display: block;
text-align:right;
}
<div class="overall" id="btn">
click to launch modal
</div>
<div class="modal" id="dialog" style="display:none">
<span id="close"> close</span>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With