I have an iframe on a page on the same domain. I need to get the scrollheight of the page which is displayed in the iframe to determine whether the vertical scrollbar is displayed or not. For example, if (iframe document height > iframe window height) it means that scrollbar is displayed. Iframe window height is a constant value defined by CSS (320px) but how can I get the document height of the page displayed in the iframe?
I did a little playing around with local files and I think the issue has more to do with waiting for the entire page to finish loading. Try this JavaScript on your page:
function getIframeDocHeight() {
'use strict';
var iframeDocHeight = document.getElementById('myiframe').contentWindow.document.getElementsByTagName('body')[0].scrollHeight;
return console.log(iframeDocHeight);
}
window.onload = getIframeDocHeight;
You can also use this value instead for iframeDocHeight:
var iframeDocHeight = document.getElementById('myiframe').contentDocument.body.scrollHeight;
Thanks for your help. I tried displaying that scrollheight value using alert() without any success. Which variable should I use? Additionally, what is “use strict” used for and what does “console.log” do?
Once in Chrome, press F12 to open the dev tools, then click the console tab.
There you should see the output of console.log (if not, just reload the page).
Many people use alert() for this purpose but console.log() is easier to work with, as using an alert pop-ups up a modal dialog box that blocks the user interface.
Also, when trying to debug a JavaScript problem on a web page, the console is the first place you should look, as all errors are logged there.
From my local test files it didn’t seem to matter which value you gave the iframeDocHeight variable. I was getting the same numbers regardless of which value I used. I should point out I was getting different values depending on which browser I was testing in. Opera had a different value from Firefox.
‘use strict’ invokes strict mode for your entire script or individual functions. “ECMAScript 5’s strict mode is a way to opt in to a restricted variant of JavaScript.”[1]
As Pullo mentioned, Chrome is not the only browser with developer tools for debugging your JS. You should definitely check out Opera’s Dragonfly tool and Firefox’s Firebug Add-on. Essential tools for any web developer! You might want to also bookmark JSHint (http://jshint.com/) for checking your JS code quality.