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>

   
      

Run codeHide result


+3


source to share


2 answers


This is a recently added Chromium feature called scroll commit.

Disable in Browser: Go to chrome://flags/#enable-scroll-anchoring

and set the Anchor Scrolling option to Disabled.



Disable via CSS:

.some-element {
    overflow-anchor: none;
}

      

+3


source


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
}

      

0


source







All Articles