Freeze body scroll without body width jump
HTML
<div class="main longcontent">
<button>Open Modal</button>
<br>
<button>Open Modal</button>
<br>
<button>Open Modal</button>
</div>
<div class="modal">
<div class="longcontent">
<button>Close Modal</button>
<br>
<button>Close Modal</button>
<br>
<button>Close Modal</button>
</div>
</div>
CSS
.longcontent {
margin: 25% 5%;
line-height: 300px;
text-align:center;
background: green;
}
.modal {
position: fixed;
overflow: auto;
top: 9%;
right;
9%;
left: 9%;
bottom: 9%;
top: 0;
right;
0;
left: 0;
bottom: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
}
.modal .longcontent {
background: yellow;
margin: 10% 20%;
}
JavaScript
$(function () {
var $body = $(window.document.body);
function bodyFreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('overflow', 'hidden');
$body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}
function bodyUnfreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
$body.css('overflow', 'auto');
}
$('.modal').hide()
$('.longcontent.main button').click(function () {
$('.modal').show()
bodyFreezeScroll()
})
$('.modal button').click(function () {
$('.modal').hide()
bodyUnfreezeScroll()
})
})