Reputation: 2879
I am running in to an issue with Firefox and Safari where when trying to get the .offset().top value from an element in an iframe, I am getting undefined back when trying to get this value. This seems to work fine in Chrome, Edge and IE, but not in Firefox or Safari.
Here's the URL:
https://twlatl.github.io/styleguide/
When you click the navigation in Firefox, you'll see the error in the console.
TypeError: this.$iframeContent.find(...).offset(...) is undefined
The block that is causing problems is here:
gotoAnchor: function($elem) {
window.location.hash = '!' + $elem.attr('href').replace('#', '');
this.top = this.$iframeContent.find('h1' + $elem.attr('href')).offset().top;
this.$iframeContent.find('html, body').animate({
scrollTop: this.top
}, 800);
},
Removing the .offset().top from the element removes the error, but also removes the ability to scroll to that portion of the page.
I've tried wrapping this variable in an .on() method to check that the iframe is fully loaded first, but that doesn't work.
Upvotes: 0
Views: 1287
Reputation: 9471
Try this (you can restructure to meet your needs)
var iframe = document.body.querySelector('.hgt-iframe-wrapper > iframe')
var iframeBody = iframe.contentDocument.body
var sectionHeader = iframeBody.querySelector($elem.attr('href'))
if( sectionHeader ){
sectionHeader.scrollIntoView()
}
Note: you'll get an error with this ^ because ID's aren't allowed to start with numbers. Change the section header ID's to start with a letter and it will work
Ah, your problem is your are accessing the content of your iframe before its loaded. If you refresh sometimes it loads fast enough and your menu works. You can see in the screenshot below that the iframe was not loaded fast enough and so this.$iframeContent
is effectively empty (no <div>
s returned)
Upvotes: 2