4

Parent and iframe are on the same domain. Iframe has dynamic height and no scrollbars of its own - scrollbars are on the parent window.

Despite much searching, I can't find a way of scrolling the parent window to an anchor in the iframe on loading. ie the iframe url is abc.com/iframe.html#link, but on loading only the top of the iframe is visible - the parent frame doesn't scroll to #link. Does anyone know of a way this can be done with javascript (in either the parent or the iframe or both) or otherwise?

Thanks

3 Answers3

2

This can be done though javascript.Suppose you click on a link, instead of anchor linking it, try this:

document.getElementById('id_of_link').scrollIntoView(true);

Edit: What about window.parent.scroll(x,y) where x,y are the positions of the elements retrieved through this method:

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left;

From: Retrieve the position (X,Y) of an HTML element

Community
  • 1
  • 1
ppsreejith
  • 3,318
  • 2
  • 25
  • 27
  • Thanks, but I've tried this and it doesn't work in the iframe as it's the parent that needs to scroll not the iframe and it doesn't scroll to the id_of_link from the parent (even assuming I could find the id_of_link from the hash value of the iframe from the parent). – Ruth Edmondson Jun 16 '12 at 12:11
  • The edited solution works sometimes in Chrome, not in Firefox. As the original page works with just links in IE9 (no javascript needed), I've decided to leave well alone, but thanks for your help - much appreciated. – Ruth Edmondson Jun 18 '12 at 07:20
0

Did you try urlencoding the #?

Try: %23

huhuh
  • 31
  • 4
-1

Try this

onscroll = (event) => {
    event.stopPropagation();
    event.preventDefault();

    window.scrollTo(0, 0); // scroll parent window to anchor in iframe
    return false;
};
sp42
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Nov 10 '22 at 02:15