I am trying to display my iframe on any website like this one HERE but for some reason the height is not calculated correctly. I get 8px on the style tag instead of 1000+ to display correctly that block.
<iframe id="iframe" allowtransparency="true" frameborder="0" style="width:100%; border:none" scrolling="no" src="http://newskillsacademy.co.uk/affiliates/iframe.php?&products_ids[]=55072&products_ids[]=51883&products_ids[]=49321&products_ids[]=48561&products_ids[]=48398&products_ids[]=46469&products_ids[]=44080&products_ids[]=43167&products_ids[]=42427&products_ids[]=41068&columns=3&aff_id=3"></iframe>
<script>
var frame = document.getElementById('iframe');
frame.style.height = 0;
frame.style.height = frame.contentWindow.document.body.scrollHeight + 'px';
</script>
The line that sets the height (i.e. frame.style.height = frame.contentWindow.document.body.scrollHeight + 'px';) is likely run before the contents of the iframe have loaded. Thus in order to set the height properly, that code must be executed after the contents of the iframe have loaded.
One way to do this is to assign the onload property to a function containing the code to set the height property:
var frame = document.getElementById('iframe');
frame.onload = function() {
frame.style.height = frame.contentWindow.document.body.scrollHeight + 'px';
}
See this demonstrated here.
Also, the code attempts to fetch the iframe from the DOM as soon as the javascript executes. Depending on the location of the script tag/file (e.g. loaded via <head> or <body>) the DOM may not be ready. One solution to this is waiting for the DOMContentLoaded event. This can be achieved using EventTarget.addEventListener() on document.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
And because you initially tagged the question with jQuery, the .ready() method provides a shortcut to this.
$(document).ready(function(event) {
console.log("DOM is safe to manipulate");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a javascript in the head tag of a domain that is not mine that is looking for DIVs on the page to measure the height and width. The names of the DIVs are in an array. Each div has an undefined size. The size of the div will grow based on an iframe that loads from a different domain. The div may not always be the same size as the iframe so the div is not a reliable element to pull the size of. Therefore, I must measure the iframe. However, my problem is that my code loads in the head and sometimes loads before the div's size is defined which means the iframe isn't ready yet. I then do a setTimeout to check if the div's height and width is greater than 1. However, I notice that after the div and iframe content visually appears on the screen, there is a delay of a few seconds before the console logs the size of the iframe. I need the dimensions as soon as the iframe content loads. How can I make this code more efficient?
Head Tag of Page
var oDv = ["div-0", "div-1", "div-2"];
<script src="mydomain.js"></script>
Body of Page
<div id="div-0">
<script src="gets-an-iframe-from-some-other-domain.js"></script>
mydomain.js (aka my script)
window.addEventListener('load', pageFullyLoaded, false);
function pageFullyLoaded(e) {
var index;
for (index = 0; index < oDv.length; index++){
measure(oDv[index]);
}
}
function measure(div){
var divElement = document.getElementById(div);
if(divElement === null){
return;
}
var iframeElement = document.getElementById(div).getElementsByTagName('iframe')[0];
var iframeDimensions = window.getComputedStyle(iframeElement, null);
var iframeHeight = parseInt(iframeDimensions.getPropertyValue("height"));
var iframeWidth = parseInt(iframeDimensions.getPropertyValue("width"));
if((iframeHeight || iframeWidth) == 1){
timer();
}
else{
console.log(iframeHeight+" "+iframeWidth);
}
}
function timer(){
var T = setInterval(function(){
if((iframeHeight || iframeWidth) == 1){
iframeHeight = parseInt(iframeDimensions.getPropertyValue("height"));
iframeWidth = parseInt(iframeDimensions.getPropertyValue("width"));
}
else{
clearInterval(T);
}
}, 100);
UPDATE 1
I think I need to work around the window.addEventListener('load', pageFullyLoaded, false); because sometimes the first DIV loads while the rest of the page content is still loading. And sometimes the iframe loads before the page content is done. Therefore the top DIV/iframe are ready to be measured but my code hasn't started because it is still waiting for the the entire page to load. Also, I'd like to get away from using the setTimeout if possible.
UPDATE 2
I tried the following code but I get the following error: "Uncaught TypeError: Cannot read property 'getElementsByTagName' of null". I believe this is because when I check for this the DIV exists but the iFrame does not yet. I don't want to try adding an event listener to the window for the page to have loaded because I need the size as soon as possible.
function iframeReady(div){
console.log(div+' Start Function');
var iframe = document.getElementById(div).getElementsByTagName('iframe')[0];
iframe.onload = function() {
console.log('iFrame loaded');
var iframeDimensions = window.getComputedStyle(iframe, null);
var iframeHeight = parseInt(iframeDimensions.getPropertyValue("height"));
var iframeWidth = parseInt(iframeDimensions.getPropertyValue("width"));
console.log('iframeLoaded '+div+' iframe dimensions: '+iframeWidth+'x'+iframeHeight);
}
}
iframeReady('a-div-id');
In the above I see the following in the console:
a-div-id Start Function
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
I guess I'll just need to put the above into a settimeout loop to keep checking for the existence of the iframe first?
Try to use the iframe.onload event
var iframe = document.getElementByTagName("iframe")[0];
iframe.onload = function() {
console.log(iframe.getBoundingClientRect());
}
I have a iFrame on my page thats display style is none. I have a javascript function to set the source and then set the display to block. The problem is that the iframe shows up before the content of it is loaded and thus I get a flickering effect. It goes white first and then displays the content. So I need to set the source, and when done loading all content of its source, only set its display style.
CSS & Javascript
.ShowMe{display:block;}
function(url)
{
document.getElementById('myIFrame').src = url;
document.getElementById('myIFrame').className = ShowMe;
}
It's simple as that:
<iframe onload="this.style.opacity=1;" style="opacity:0;border:none;
I would suggest you try the following:
<script type="javascript">
var iframe = document.createElement("myIFrame");
iframe.src = url;
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera){
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
//not sure if your code works but it is below for reference
document.getElementById('myIFrame').class = ShowMe;
//or this which will work
//document.getElementById("myIFrame").className = "ShowMe";
}
};
}
else
{
iframe.onload = function(){
//not sure if your code works but it is below for reference
document.getElementById('myIFrame').class = ShowMe;
//or this which will work
//document.getElementById("myIFrame").className = "ShowMe";
};
}
</script>
Based on the code found here.
You could do this within the iframe:
window.onload = function () {
window.frameElement.className = 'ShowMe'; // 'ShowMe' or what ever you have in ShowMe variable.
}
Since you've tagged your question with [jquery], I assume you have executed the code within $(document).ready(). It is fired when the DOM is ready, i.e. it uses native DOMContentLoaded event (if available). window.onload is fired, when all resources on the page are ready.
I have an iframe that I would like to resize to match its contents whenever the contents auto refreshes (every few minutes) or when the user interacts with it. Although the contents are in the same domain, it would be difficult for me to modify the contents. Ideally, the iframe would just self adjust to the size of its contents.
Current code that resizes only once:
<iframe id="ganglia-frame" src="ganglia.url" width="100%" height="500%">
blah not supported blah
</iframe>
<script language="Javascript">
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow ||
iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height =
iframeWin.document.documentElement.scrollHeight ||
iframeWin.document.body.scrollHeight;
}
}
}
$(window).load(function () {
setIframeHeight(document.getElementById('ganglia-frame'));
});
</script>
Related question: Adjust width height of iframe to fit with content in it
What you need to do is to set a timer and check the iFrame size after a few moments. You may have to check several times as not all browsers return the correct size immediately.
This method works only on same-domain iFrames.
Bind a function to the iFrame onload event and when it executes check the height of the iFrame. If no height is found schedule another check in a few moments.
var iFrameSizeCount = 0;
var onloadFunction = function(event){
var contentHeight = document.getElementById('iFrameId').contentWindow.document.body.offsetHeight;
if(contentHeight == 0){
// Schedule a recheck in a few moments
iFrameSizeCount++; // we keep a count of how many times we loop just in case
if(iFrameSizeCount < 10){ // after a while we have to stop checking and call it a fail
setTimeout(function(){ onloadFunction(event); }, 200);
return false;
}
else {
contentHeight = 100; // eventually if the check fails, default to a fixed height. You could possibly turn scrolling to auto/yes here to give the iFrame scrollbars.
}
}
contentHeight += 30; // add some extra padding (some browsers give a height that's slightly too short)
document.getElementById('iFrameId').style.height = contentHeight + 'px';
}
Then bind the event to the onload event of your iFrame (however you want to):
The "scrolling=auto" is useful, just in case the sizing fails at least they have scrollbars. The onload event fires if the iFrame reloads, so is useful if they've clicked a link inside it.
I have had good luck with this jQuery plugin - https://github.com/davidjbradshaw/iframe-resizer
I'm fairly new to Javascript in general, and I cobbled together a small script from things found mostly on this site to try to get a small iframe to cycle through a bunch of links, which it does brilliantly. However, I also want it to stop cycling when the user clicks on the iframe or any of its contents.
Here is the code I have so far. There is only one iframe on the HTML page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
<!--
var sites = [
"side/html5.html",
"side/silverlight.html",
"side/wordpress.html",
"side/mysql.html",
"side/php.html",
"side/css3.html"
];
var currentSite = sites.length;
var timerId;
var iframeDoc = $("iframe").contents().get(0);
$(document).ready(function ()
{
var $iframe = $("iframe").attr("src","side/html5.html");
timerId = setInterval(function()
{
(currentSite == 0) ? currentSite = sites.length - 1 : currentSite = currentSite -1;
$iframe.attr("src",sites[currentSite]);
}, 4000);
$(iframeDoc).bind('click', function()
{
clearInterval(timerId);
});
});
//-->
</script>
</head>
<body>
<sidebar>
<iframe name="sideframe" src="side/html5.html"></iframe>
</sidebar> ..etc..
Please help, I am trying to learn Javascript as fast as I can but as far as I can see, it should work, but it really doesn't.
Thanks for any help you can give me, it's really appreciated.
EDIT:
Okay, I've got a new script now, mostly based off of Elias' work, but it doesn't work either. I've pinned it down in Firebug and it's saying that the timerCallback.currentSite value IS updating properly, though I can't find the $iframe's src value to check for it explicitly. As far as I can tell, it is updating the variables properly, it's just not updating the iframe properly. Am I calling/setting the iframe correctly in this code? Also, is the linked in jquery library sufficient for my purposes? I'm a little lost of all these libraries to link to...
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
<!--
var sites =
[
"side/html5.html",
"side/silverlight.html",
"side/wordpress.html",
"side/mysql.html",
"side/php.html",
"side/css3.html"
];
var $iframe = $("iframe").attr("src","side/html5.html");
function timerCallback()
{
timerCallback.currentSite = (timerCallback.currentSite ? timerCallback.currentSite : sites.length) -1;
$iframe.attr("src",sites[timerCallback.currentSite]);
$($('iframe').contents().get('body')).ready(function()
{
$(this).unbind('click').bind('click',function()
{
var theWindow = (window.location !== window.parent.location ? window.parent : window);
theWindow.clearInterval(theWindow.timerId);
});
});
}
var timerId = setInterval(timerCallback, 4000);
//-->
</script>
If I were you, I'd play it safe. Since you say you're fairly new to JS, it might prove very informative.
function timerCallback()
{
timerCallback.currentSite = (timerCallback.currentSite ? timerCallback.currentSite : sites.length) -1;
$iframe.attr("src",sites[timerCallback.currentSite]);
}
var timerId = setInterval(timerCallback, 4000);
$($('iframe').contents().get('body')).unbind('click').bind('click', function()
{
var theWindow = (window.location !== window.parent.location ? window.parent : window);
theWindow.clearInterval(theWindow.timerId);
});
Now I must admit that this code is not tested, at all. Though I think it provides a couple of things to get you on your way:
1) the interval is set using a callback function, because it's just better for tons of reasons
1b) in that Callback, I took advantage of the fact that functions are objects, and created a static var, that is set to either the length of your sites array (when undefined or 0), in both cases 1 is substracted
2) jQuery's ,get() method returns a DOM element, not a jquery object, that's why I wrapped it in $(), a new jQ obj, giving you the methods you need.
3) since you're manipulating the dom inside the iFrame, it's best to unbind events you want to bind
4) inside the iFrame, you don't have direct access to the parent window, where your interval is.
You might want to read up on how to deal with iFrames, because they can be a bit of a faff from time to time
EDIT:
David Diez is right, easiest way around this is to incorporate the binding in the timeout function:
function timerCallback()
{
timerCallback.currentSide = ...//uncanged
//add this:
$($('iframe').contents().get('body')).ready(function()
{
$(this).unbind('click').bind('click',function()
{
//this needn't change
});
});
}
In theory, this should bind the click event to the body after it has been loaded
Edit2
I've been messing around a bit, you could keep your code, as is. just add a function:
function unsetInterval()
{
window.clearInterval(window.timerId);
}
and add this to your setInterval function:
$('#idOfIframe').load(function()
{
var parentWindow = window.parent;
$('body').on('click',function()
{
parentWindow.clearInterval();
});
});
this will get triggered as soon as the iFrame content is loaded, and bind the click event and unset the timer, like you wanted to
I think your code is not working because of this
var iframeDoc = $("iframe").contents().get(0);
This could be getting the header of the iFrame because you are saving the iframeDoc value to the first child of the iframe, the head tag, actually if you have more than 1 iframe in your window iframeDoc would be undefined because $("iframe") gets all the iframes of your document.
BTW your currentSite value condition is wrong, you asign the same value for both conditions
Now I give you an example:
<iframe id="myFrame" src="http://www.google.com/"></iframe>
and the script:
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var sites = [
"site1",
"site2"
];
var myFrame = document.getElementsByTagName('iframe')[0];
var currentSite = myFrame.getAttribute('src');
var timerId;
var myFrameDoc = window.frames[0].document;
$(document).ready(function()
{
myFrame.setAttribute('src', 'side/html5.html');
timerId = setInterval(function()
{
//WRONGG
(currentSite == 0) ? currentSite = sites.length - 1 : currentSite = currentSite -1;
myFrame.setAttribute('src', sites[currentSite]);
$(myFrame).off("click").on("click", clearInterval(timerId));
}, 4000);
//Won't work because you are trying to get events from an inside of a iframe
//$(myFrameDoc).on("click", clearInterval(timerId));
//This may work
$(myFrameDoc).off("click").on("click", clearInterval(timerId));
});
</script>
When you try to track the events of an iframe you have to be carefull because an iframe contains a totally different document for javascript purprouses so basically you have to get inside the new document, unbind the events you need to use, and bind them again against your functionality, as #Elias points out. but be aware that you are changing constantly the src of your iframe, so if yu really need to do that you will have to separate the code that unbinds and binds again your clearInterval, and for that matter maybe $.on() could work for you.
EDIT: Calling to the iframe should work this way IF the src of the iframe is inside the same domain, with the same port and with the same protocol:
var myFrameDoc = window.frames[0].document;
I Added a new variable because we want to bind and unbind the click event to the iframe's document, not to the iframe, we use for that the window.frames collection property, but modern browsers throw an exception and denies acces if you try to access to a frame and you are not on the same domain with using the same port and the same protocol...
Additionaly the use of $.on() and $.off() instead of $.bind and $.unbind() is because the first ones are the new ones and despite we are not using it here, they are capable of watch constantly the DOM for new elements to bind if added; that could be useful to this case if this code still doesn't work. If that is the case you can still change this:
var myFrameDoc = window.frames[0].window;
and this:
$(myFrameDoc).off("click", "document").on("click", "document", clearInterval(timerId));
This will re-bind the event handler to new documents additions. Not tested but could work.