iframe on the page bottom: avoid automatic scroll of the page

Viewed 22475

I have an iframe from the middle to bottom on a page. When I load the page it scrolls to the bottom. I tried to body onload window.scroll(0,0) but it does an ugly effect because it first goes down and then immediately scrolls up.

What's the cause of this automatic scroll to bottom with iframe on the page?

7 Answers

I came up with a "hack" that works well. Use this if you don't want your webpage to be scrolled to anywhere except the top:

// prevent scrollTo() from jumping to iframes
var originalScrollTo = window.scrollTo;

window.scrollTo = function scrollTo (x, y) {
  if (y === 0) {
    originalScrollTo.call(this, x, y);
  }
}

If you want to disable autoscrolling completely, just redefine the function to a no-op:

window.scrollTo = function () {};

This seems to work well:

<iframe src="http://iframe-source.com" onLoad="self.scrollTo(0,0)"></iframe>

This is the solution I came up with and tested in Chrome.

We have an iframe wrapped by a div element. To keep it short, I have removed the class names related to sizing the iframe. Here, the point is onMyFrameLoad function will be called when iframe is loaded completely.

<div class="...">
    <iframe onload="onMyFrameLoad()" class="..." src="..."></iframe>
</div>

Then in your js file, you need this;

function noscroll() {
  window.scrollTo(0, 0);
}
// add listener to disable scroll
window.addEventListener('scroll', noscroll);
function onMyFrameLoad() {
  setTimeout(function () {
    // Remove the scroll disabling listener (to enable scrolling again)
    window.removeEventListener('scroll', noscroll);
  }, 1000);
}

This way, all the scroll events become ineffective till iframe is loaded. After iframe is loaded, we wait 1 sec to make sure all the scroll events (from iframe) are nullified/consumed. This is not an ideal way to solve your problem if your iframe source is slow. Then you have to wait longer by increasing the waiting time in setTimeout function.

I got the initial concept from https://davidwells.io/snippets/disable-scrolling-with-javascript/

Related