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?
The
src="about:blank"
trick provided by Leandro & edited by Spokey worked for me, but I'd like to share a workaround I was using before.A temporary solution I found was to embed the iframe in the uppermost element on my page (nav, header etc), so that even if the browser wants to jump to focus, it 'jumps' to the top element. This still can cause a slightly perceptible jump, which might bug you.
To make sure the iframe remains hidden if you choose to place it near the top of a page, I applied an inline style of
style="visibility:hidden; height: 0px; width: 0px;"
. I guess you could also use az-index
combo.This seems to work well:
Simple. Use
about:blank
insrc
likeI 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:
If you want to disable autoscrolling completely, just redefine the function to a no-op:
This is just a random one, but possible doing something like this:
The thinking being that if it is some focus stealing script on a remote page that you can't control, the browser won't focus a hidden element. And there's a good likelihood that your onload will fire after their focus changing script.
Or, one other option that might be a bit more reliable:
Here we're basically saying hiding the frame and moving it to a negative offset on the page vertically. When it does try to focus the element inside of the frame, it should scroll the page upward, then once loaded place the iframe back in it's intended position.
Of course, without knowing more, it's hard to say for sure which tradeoffs are okay, and both of these options have conditions that are a tad racy, so YMMV.
I hope that helps :)
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.
Then in your js file, you need this;
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/