The script below adds a smooth scrool effect when clicking on anchor links in a web page.
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
Works on most modern browsers, including mobile browsers for iOS and Android. However, if the script is run inside an iframe, browsers on iOS don't apply the smooth scrool effect. In fact, anchor links are rendered useless (if the user clicks on one, nothing happens). Even when inside an iframe, the script works on Android and virtually all desktop browsers.
iOS has all sorts of problems with iframes. For example, even if an iframe has a declared height of 300px, iOS expands the height of the iframe to fit the content, with no scrolling inside. The fix for this: wrap the iframe in a div with a height of 300px and add overflow: auto;
and -webkit-overflow-scrolling: touch;
.
Back to my problem. Why does such a simple script fail on iOS in an iframe? Could this be related to the way iOS handles iframes (described above)?
To clarify things, I need the smooth scroll effect to work inside the iframe on iOS. Iframe and parent document are both served from the same domain.
Anyone, any idea?
For a working example please see here: http://www.nightskyinfo.com/iframe2/
Source code of the main html file: http://www.nightskyinfo.com/iframe2/index.txt
Souce code of the html file put in the iframe here: http://www.nightskyinfo.com/iframe2/iframe.txt
If the script is run inside an iframe, the jQuery selector $
will look for elements in the iframe's document, not in the parent document. This is the selector context. To look for element in the parent document, you can indeed specify the parent document by doing $('html, body', parent.document)
(or top.document
).
However, to access the parent document from a frame, the frame domain must be the same than the parent one. Check that point.
Something not obvious to understand in your request is which document you finally need to scroll ? the parent one or the frame one ?
Another thing, can't get what you are trying to achieve with this:
$( $.attr(this, 'href') ).offset().top
imho, this selector will match nothing. Except if you are storing CSS selector as href
value...
I guess your are looking for something simpler (and working btw) with:
$(this).offset().top
Hope I helped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With