Why Alert 'locks' the scroll?
The boxes of alert()
, confirm()
and prompt()
are in a layer outside the programming bubble of your website. It means that you have limited control over them. Who exercises all control is the browser you are using.
When a dialog box is displayed all the content of the site gets stuck. The scrollbar doesn’t work, just like a mouse click or any other algorithm running at that time. This happens because the execution of these methods in Javascript is synchronous, so the code will only be continued after a user action.
Take 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?
On Soen has an answer on how you can disable the scroll of your website. In response, it captures the scrolling events of the mouse and touch devices and executes the preventDefault()
, that cancels the current and subsequent action to the event.
See an outline:
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>
Actually, it doesn’t override the scroll. It’s just a browser dialog window that blocks access to the window while it’s not closed, just like any other application.
– Sam
You can’t block the scroll, but you can prevent the scroll by disabling all the interactions the user may have with the page. You can do a btn that disables the mouse scroll, Touche and the keys that scroll.
– hugocsl
@dvd I understand! Disable, remove already done this, for example in a simple modal, which occupies the entire screen, I disable the html scroll, and at the same time put a padding-right:16px; to compensate. There’s a delay, so I was wondering if it might be possible to override.
– John Quimera
But it is not a very good practice to put padding to compensate, since the width of the scroll can suffer browser variations to browser.
– Sam