Skip to content

Instantly share code, notes, and snippets.

@ssshake
Last active January 4, 2019 21:00
Show Gist options
  • Save ssshake/f0de2cd47d3110380f69b74583047d99 to your computer and use it in GitHub Desktop.
Save ssshake/f0de2cd47d3110380f69b74583047d99 to your computer and use it in GitHub Desktop.
//So, it's a pain in the ass to use scrollTo within an iframe because
//the parent document and the document in the iframe have no context of each other.
//
//The problem can be hard to imagine if you haven't directly ran into it before, but lets assume you have
//a parent document that is a couple thousand pixels high. It spans off the screen.
//In that document you have an iframe somewhere near the top (or wherever)
//Under some condition you want to scroll to the top (or anywhere) of the iframe
//But lets say in the parent document you a scrolled all the way to the bottom so the iframe isn't in view at all
//When you issue window.scrollTo(0,0), the iframe itself will scroll to the top, but the parent document wont do anything.
//Why would it? It has no context.
//What you actually wanted was for the iframe to scrollTo(x,y) but also for the parent document to scrollTo(iframe.x,iframe.y)
//Now if you have control of the parent documents source code you can simply add an ID or name to the iframe element and reference that
//BUT what if you have no control over the parent document what so ever? This sounds like a corner case I know, but it's come up
//often enough that I have scratched my head many times before and have decided to document it.
const iframeDocumentTitle = "test123" // This is not the title of the iframe element in the parent. This is the title of the HTML document inside of the iframe. You have control over this HTML document in the iframe, you do not (in this example) have control over the iframe element so you cannot change the title. That is the trick.
const iframe = Array.prototype.slice.call(parent.document.getElementsByTagName("iframe")).find((frame)=>{
return frame.contentDocument.title === iframeDocumentTitle;
});
if (iframe){
parent.scrollTo(0, iframe.offsetTop); //If your HTML document is in an iframe, this will scroll to the top of the iframe bringing it into view.
}
window.scrollTo(0,0); //Whether your HTML is in an iframe or not, you want to scroll to a position within the document(top in this case)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment