Why the alert 'hangs' the scroll?
The boxes for alert()
, confirm()
and prompt()
are in a layer outside the bubble of your site's programming. That means you have limited control over them. Whoever exercises all the control is the browser you are using.
When a dialog box is displayed all site content gets stuck. The scrollbar does not work, just like a mouse click or any other algorithm that is running at that moment. This happens because the execution of these methods in Javascript is synchronous, so the code will only be continued after a user action.
See an example:
var intervalo = setInterval(function(){
console.log("Oi");
}, 1000);
function travar() {
alert("Este alert 'travou' todo o site! Veja que o console.log não exibe mais o 'Oi'.");
}
<a href="#" onclick="travar()">Clique aqui</a>
How to block the scroll?
No SOen has an answer about how you can disable the scrolling of your site. In the response, it captures mouse and touch device scrolling events and runs preventDefault()
, which cancels the current and post-event action.
See a sketch:
function desativar() {
var div = document.getElementById("conteudo");
if (window.addEventListener) { // navegadores antigos
window.addEventListener('DOMMouseScroll', preventDefault, false);
}
div.onwheel = preventDefault;
div.onmousewheel = document.onmousewheel = preventDefault; // navegadores antigos, IE
div.ontouchmove = preventDefault; // mobile
console.log("Desativado!");
}
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
<div id="conteudo" style="overflow: overlay; width: 150px; height: 100px;">
<p>Linha1</p>
<p>Linha2</p>
<p>Linha3</p>
<p>Linha4</p>
<p>Linha5</p>
<p>Linha6</p>
<p>Linha7</p>
<p>Linha8</p>
</div>
<p><a href="#" onclick="desativar();">Desativar Scroll</a></p>