Stop auto scrolling when page content changes
I have a page that adds and removes some content for itself in a scroll event.
Now when you are using Chrome (IE11 doesn't seem to have this behavior), whenever content is added and removed to the page, a scroll event is generated (I think to keep the client view persistent across page changes).
I do not want it. A scroll event generated when content changes will trigger more content changes, which in turn will trigger more scroll events.
Any advice on how I can stop this behavior for all browsers? I don't need auto scrolling. I want custom scrolling to register.
Here are some simple code examples. Pressing the "click" button will swap the color differences and make the page scroll on its own (in Chrome, not IE11) ...
function removeStuff(){
var elem = document.getElementById("center");
document.getElementById("container").removeChild(elem);
document.getElementById("container").appendChild(elem);
}
#top {
background-color: green;
height:1500px;
}
#center {
background-color: blue;
height:1000px;
}
#bottom {
background-color: red;
height:1500px;
}
<div id="container">
<div id="top"></div>
<div id="center"></div>
<button id="button" onclick="removeStuff()">click</button>
<div id="bottom"></div>
</div>
source to share
I don't think you can disable this behavior, but you can work around it. Since Chrome executes the event scroll
synchronously when you call removeChild
, you can detect these types of scroll events by setting a global boolean value to true
immediately before removeChild
and returning it back to false
immediately after.
var isRemovingStuff = false;
function removeStuff(){
var elem = document.getElementById("center");
// Chrome does a scroll here, set isRemovingStuff to true
// so our scroll handler can know to ignore it.
isRemovingStuff = true;
document.getElementById("container").removeChild(elem);
isRemovingStuff = false;
document.getElementById("container").appendChild(elem);
// TODO: set the scrollTop back to what you want it to be.
}
And your scroll handler will look like this:
function onScroll() {
if (isRemovingStuff)
return;
// Do cool stuff
}
source to share