JavaScript getElementById(...) is null or not an object IE - javascript

This must be something very simple for the JavaScript experts out there. In the following code, I am trying to open an iframe to the full height of browser window.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function resizeIframe() {
var height = document.documentElement.clientHeight;
height -= document.getElementById('documentFrame2').offsetTop;
height -= 20;
document.getElementById('documentFrame2').style.height = height +"px";
};
document.getElementById('documentFrame2').onload = resizeIframe;
window.onresize = resizeIframe;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<iframe src="standard-tube-map.pdf" id="documentFrame2" width="100%" onload="resizeIframe();" ></iframe>
</div>
</form>
</body>
</html>
It works in Mozilla but in IE (only tested in IE8) it gives the error: 'document.getElementById(...) is null or not an object'. Can anybody suggest what should I change to make it work cross browser?
Many thanks,
Ali

Try wrapping
document.getElementById('documentFrame2').onload = resizeIframe;
Within:
window.onload = function(){
document.getElementById('documentFrame2').onload = resizeIframe;
window.onresize = resizeIframe;
resizeIframe();
};
The iframe doesn't exist in the DOM until the page/Dom has loaded.
UPDATE:
Didn't see part of the code you posted.
You could keep onload = "resizeIframe" within the element itself and have the JavaScript in the head as:
function resizeIframe() {
var height = document.documentElement.clientHeight;
height -= document.getElementById('documentFrame2').offsetTop;
height -= 20;
document.getElementById('documentFrame2').style.height = height +"px";
}
window.onresize = resizeIframe;
That way you wouldn't need any JavaScript running after the element.

alert(document.getElementById('abcId').value);
alert(document.formName.elements['abcName'].value);
I expirienced the same issue i tried the 2nd one it worked.

you do
document.getElementById('documentFrame2').onload = resizeIframe;
before the document is ready so the iframe can be found. call this in the onload- or document-ready-function or in a seperate javascript-block after the iframe.

If you have used onload"resizeIframe" in the iframe tag, you don't need document.getElementById('documentFrame2').onload = resizeIframe; anymore
I prefer relacing window.onresize = resizeIframe; by:
window.onload = function() {
window.onresize = resizeIframe;
};
Sometimes the window will be resized before the iframe is ready for operation, and that would cause errors.
========================
edited:
window.onload = function() {
resizeIframe();
window.onresize = resizeIframe;
};

Related

How to auto shrink iframe height dynamically?

I use the following code to achieve dynamic iframe height:
In the <head>:
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
In the <body>:
<iframe name="myiframe" src="somepage.html" width="100%" frameborder="0"
scrolling="no" onload='javascript:resizeIframe(this);' />
</iframe>
This codes works fine with height increasing only. So, when the content inside the iframe increases in height, the iframe updates its height and increases with it.
The problem is with height decreasing or shrinking. When the content inside the iframe decreases, it doesn't decrease and causing big unwanted white space. This only occurs in Chrome, IE & FF works fine.
Here is my Page
I want to know how to make this code works to auto shrink iframe height when it decreases?
Screenshot one:
Screenshot two:
Update 1
I placed the following code in the <head>
<script src="jquery-1.10.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
});
The iframe code in the <body>
<iframe name="dservers" src="dual_core.html" width="100%" frameborder="0"
scrolling="no" /></iframe>
The iframe not showing in the page. It appears for one second and then disappears.
Update 2
I think The problem was the $ character before (function(){, I removed it. I'm sorry I don't have much experience with jquery. I updated the page and removed the onload="resizeFrame()" but the iframe doesn't act dynamically now.
Problem Solved
I was digging in the internet and I found a code solved the whole problem for me. I would like to share it so anyone can use it in order to get dynamic iframe height.
First, put the following code between the <head> tags:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(myiframeid) {
var ifrm = document.getElementById(myiframeid);
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px";
ifrm.style.height = getDocHeight( doc ) + 5+"px";
ifrm.style.visibility = 'visible';
}
</script>
<script>(function(run){
for (i=0;i<frames.length; i++) {
var f1 = document.getElementsByTagName('myiframename')[i];
if(!f1 && window.addEventListener && !run){
document.addEventListener('DOMContentLoaded', arguments.callee, false);
return;
}
if(!f1){setTimeout(arguments.callee, 300); return;}
f2 = f1.cloneNode(false);
f1.src = 'about: blank';
f2.frameBorder = '0';
f2.allowTransparency = 'yes';
f2.scrolling = 'no';
f1.parentNode.replaceChild(f2, f1);
}
})();
</script>
Second, the Iframe code in the <body> :
<iframe id="myiframeid" name="myiframename" src="somepage.html" width="100%"
frameborder="0" scrolling="no" onload='javascript:setIframeHeight(this.id);' />
</iframe>
Third and Last, the CSS:
#myiframeid{
width: 100%;
}
Note: You should have Name and ID for the Iframe.
Compatible with all browsers (Chrome, Firefox, IE).
Have a good day!
I wrote a little library that deals with all these issues and keeps the iframed sized when the content changes or the browser window is resized.
https://github.com/davidjbradshaw/iframe-resizer
I thought about it quite a bit, and think I came up with another solution that may resolve your problem from the parent document. Rather than editing the documents in your iframe. However I can't test it due to cross origin policy. Try this out and let me know how it works.
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
Hope this does it for you.
Edit: This fix would require you to remove the onload="" function.
Edit-2: You seem to have combined the two scripts. You have this:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
}
Replace that entire script with this:
$(function(){
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
});
And remove the onload="resizeFrame()" from the iframes tag.

`base` tag causes iframe to open as new window in Internet Explorer

I have a problem with the base tag which only affects Internet Explorer (versions 8, 9 and 10).
The following code is used to open dynamic content in an iframe and it functions correctly in Chrome and Firefox. It also functions correctly in Internet Explorer, but only without the <base target="_blank"/> tag. The inclusion of this tag causes the iframe to open as a new window (which makes sense, however this is not what I am trying to do.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<base target="_blank"/>
</head>
<body>
<div id="main"></div>
<script type="text/javascript">
function load_iframe(name, height, width) {
var div = document.getElementById(name);
var ifrm = document.createElement('iframe');
ifrm.id = 'iframe_' + name;
ifrm.frameBorder = 0;
ifrm.scrolling = 'no';
ifrm.noresize = 'noresize';
ifrm.marginheight = 0;
ifrm.marginwidth = 0;
if (height !== 0) {
ifrm.height = height;
}
if (width !== 0) {
ifrm.width = width;
}
div.appendChild(ifrm);
content = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head></head><body></body></html>';
if (/msie/.test(navigator.userAgent.toLowerCase()) || window.opera) {
ifrm.contentWindow.contents = content;
return ifrm.src = 'javascript:window["contents"]';
} else {
doc = ifrm.contentDocument;
doc.open();
doc.write(content);
doc.close();
return ifrm;
}
}
load_iframe('main', 250, 300);
</script>
</body>
</html>
How can I fix this issue? Unfortunately, I couldn't get the code to work in a fiddle, perhaps because it relies on <base/> being in the <head>.
I just removed the /msie/.test(navigator.userAgent.toLowerCase()) || part, and works fine on IE8. Are you sure that you need this piece of code?
However, whether you don't want remove this piece, you can remove the base tag and add it after you create the iframe:
load_iframe('main', 250, 300);
//and then:
var hd = document.getElementsByTagName("head")[0];
var bs = document.createElement("base");
bs.target= "_blank";
hd.appendChild(bs);
I tested on chrome, IE8, IE11 and works perfectly!
As said in comments target="_blank" makes the browser open a new window or tab (depends on your configuration).
Just remove it or replace by self (tested on IE8):
<base target="_self"/>

Internet Explorer 8 Messing Up My Bulletgraphs

I've created HTML and JavaScript files to display bulletgraphs, using the 'canvas' HTML5 tag. I've tried it in Chrome and it works nicely and changes width along with the size of the browser. I have to have this working in IE8, too, so I've used Excanvas, which is working in all except one way: when I resize the browser I get remnants of the valueIndicator. This only happens on IE8.
I've tried looking round for information on redrawing the canvas but I don't think this is the issue. Can anyone see where I'm going wrong, please?
EDIT
I'm keeping the complete code at the bottom, however, following advice I've cut my code down somewhat.
In IE8 it looks like this:
In Chrome it looks like this:
When I refresh the IE8 page it looks OK again.
Cut-down Bulletgraph.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bulletgraph</title>
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
</head>
<body>
<canvas id="graph1"></canvas>
<script src="Scripts.js"></script>
<script>
drawGraphs();
window.onresize=function() { drawGraphs() };
function drawGraphs() {
drawBulletGraph(getScreenWidth(),300,1000,350,"graph1");
}
</script>
</body>
</html>
Complete code:
Cut-down Scripts.js:
function drawBulletGraph (cwidth, left, right, loValue, id) {
var canvas=document.getElementById(id);
var cheight=30;
var multiplier=cwidth/(right-left);
canvas.width=cwidth;
canvas.height=cheight;
var valueIndicator=canvas.getContext("2d");
valueIndicator.lineWidth="1";
valueIndicator.moveTo((loValue-left)*multiplier,0);
valueIndicator.lineTo((loValue-left)*multiplier,cheight);
valueIndicator.fill();
valueIndicator.stroke();
}
function getScreenWidth () {
return (window.innerWidth || document.documentElement.clientWidth)/7;
}
Bulletgraph.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bulletgraph</title>
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
</head>
<body>
<canvas id="graph1"></canvas><br>
<canvas id="graph2"></canvas>
<script src="Scripts.js"></script>
<script>
drawGraphs();
window.onresize=function() { drawGraphs() };
function drawGraphs() {
drawBulletGraph(bgWidth(getScreenWidth()),300,400,450,600,700,1000,800,350,850,"graph1");
drawBulletGraph(bgWidth(getScreenWidth()),250,450,500,650,700,1200,600,350,850,"graph2");
}
</script>
</body>
</html>
Scripts.js:
function drawBulletGraph (cwidth, left, loRed, loAmber, hiAmber, hiRed, right, value, loValue, hiValue, id) {
var canvas=document.getElementById(id);
var cheight=16;
var colour="#008000";
if (value <= loRed || value >= hiRed)
{
colour="#FF0000";
}
else if (value <= loAmber || value >= hiAmber)
{
colour="#FFA500";
}
var multiplier=cwidth/(right-left);
canvas.width=cwidth;
canvas.height=cheight;
var red=canvas.getContext("2d");
red.fillStyle="#F4C3C6";
red.fillRect(0,0,cwidth,cheight);
var amber=canvas.getContext("2d");
amber.fillStyle="#F4F6C6";
amber.fillRect((loRed-left)*multiplier,0,(hiRed-loRed)*multiplier,cheight);
var green=canvas.getContext("2d");
green.fillStyle="#CCE5CC";
green.fillRect((loAmber-left)*multiplier,0,(hiAmber-loAmber)*multiplier,cheight);
var valueIndicator=canvas.getContext("2d");
valueIndicator.fillStyle=colour;
valueIndicator.strokeStyle=colour;
valueIndicator.lineWidth="2";
valueIndicator.moveTo((loValue-left)*multiplier,0);
valueIndicator.lineTo((loValue-left)*multiplier,cheight);
valueIndicator.moveTo((loValue-left)*multiplier,cheight/2);
valueIndicator.lineTo((hiValue-left)*multiplier,cheight/2);
valueIndicator.moveTo((hiValue-left)*multiplier,0);
valueIndicator.lineTo((hiValue-left)*multiplier,cheight);
valueIndicator.moveTo(((value-left)*multiplier)-(cheight/2),cheight/2);
valueIndicator.stroke();
valueIndicator.lineWidth="1";
valueIndicator.lineTo((value-left)*multiplier,cheight);
valueIndicator.lineTo(((value-left)*multiplier)+(cheight/2),cheight/2);
valueIndicator.lineTo((value-left)*multiplier,0);
valueIndicator.lineTo(((value-left)*multiplier)-(cheight/2),cheight/2);
valueIndicator.fill();
valueIndicator.stroke();
}
function getScreenWidth () {
return window.innerWidth || document.documentElement.clientWidth;
}
function bgWidth (screenWidth) {
var graphWidth=screenWidth/7;
if (graphWidth<70) {graphWidth=70;}
if (graphWidth>260) {graphWidth=260;}
return graphWidth;
}
I've managed to get a solution. It feels like a bit of a hack but it does the trick. Basically it involves drawing a white line round the canvas and filling it each time it's drawn again. The following code goes between the var valueIndicator=canvas.getContext("2d"); and the valueIndicator.lineWidth="1"; lines:
valueIndicator.fillStyle="#FFFFFF";
valueIndicator.strokeStyle="#FFFFFF";
valueIndicator.moveTo(0,0);
valueIndicator.beginPath();
valueIndicator.lineTo(0,cheight);
valueIndicator.lineTo(cwidth,cheight);
valueIndicator.lineTo(cwidth,0);
valueIndicator.closePath();
valueIndicator.fill();
valueIndicator.stroke();
valueIndicator.strokeStyle="#000000";
I've tried it in the full code and it works. If anyone has a more elegant solution, and I'm sure there must be many, I would still love to see them.

After installing flash, swfobject still wont embed video until i reload the original page

I have a simple html page with some javascript where if i click a link, it will show a flash video in a div using the swfobject.embedSWF function.
I did a test:
Uninstalled flash from my machine, then reloaded the page and clicked the link...I correctly saw no video.
I then installed flash and came back to the same page (no reload) and the embed still won't work.
I know in swfobject 1.5 (I'm now using 2.2), I would be able to embed the swf after the user installs flash, but now the user needs to reload the page in order to get the flash to appear. This is not good for my current situation, anyone know what is going on here?
Here is sample code using a youtube video:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SWFOBJECT TEST</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js' type='text/javascript'></script>
<script src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js' type='text/javascript'></script>
<style>
#link{
display:block;
margin-bottom:10px;
}
#videoContainer{
width:610px;
height:360px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#link").click(function(){
var flashVars = {};
var params = {};
flashVars["lang"] = "en";
params["menu"] = "false";
params["wmode"] = "opaque";
params["allowScriptAccess"] = "always";
params["allowFullScreen"] = "true";
params["bgcolor"] = "#fff";
//add video
swfobject.embedSWF("http://www.youtube.com/v/uZ0LL1SJ-6U?enablejsapi=1&playerapiid=ytplayer", "videoContainer",640, 480, "9.0.0", null, flashVars, params,{});
});
});
</script>
</head>
<body>
Click me
<div id="videoContainer"></div>
</body>
</html>
If you take your swfEmbed call out of the jquery, it works. I didn't really delve in to far, but I did this:
Click me
I made a new function called replaceDiv, which basically just does everything you are already doing in your jquery click function.
function replaceDiv () {
var flashVars = {};
var params = {};
flashVars["lang"] = "en";
params["menu"] = "false";
params["wmode"] = "opaque";
params["allowScriptAccess"] = "always";
params["allowFullScreen"] = "true";
params["bgcolor"] = "#fff";
//add video
swfobject.embedSWF("http://www.youtube.com/v/uZ0LL1SJ-6U?enablejsapi=1&playerapiid=ytplayer", "videoContainer",640, 480, "9.0.0", null, flashVars, params,{})
}
I then removed all of your existing JS and VOILA- works every time.
Let me know if you want me to actually try to debug your JQuery; I might add that it looks perfectly fine. You may be needing something else, I don't know.
-A
ps. Squarepusher is a BEAST. :P

JavaScript only works when page is reloaded

I have a fairly simple page that displays an image in a pop-up window. The onLoad event simply takes the querystring, populates an image tag with that value, then resizes the image and window to match.
For some reason, this only works for me when the page is reloaded/refreshed. Or, once the image has been displayed once, it will work from then on, even though caching is turned off. But any time an image is viewed the first time, the page comes up blank with no errors thrown.
Any suggestions?
Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Zoom</title>
<meta http-equiv="Pragma" content="no-cache" />
<script type="text/javascript">
function getImage() {
//get the query string (everything after the ?)
var filename = window.location.search.substring(1);
//find the image control
var imageWorking = document.getElementById('dynamicImage');
//assign the image source
imageWorking.src = '../Images/' + filename;
//create an image variable
var newImg = new Image();
//assign the source to match the page image
newImg.src = imageWorking.src;
//get the width and height
var width = newImg.width;
var height = newImg.height;
//set the page image width and height to match the disk image
imageWorking.width = width;
imageWorking.height = height;
//set the window to be just larger than the image
window.resizeTo(width + 50,height + 50);
}
</script>
</head>
<body onload="getImage();">
<img src="images/spacer.gif" id="dynamicImage" alt="Image Zoom" width="1" height="1" />
</body>
</html>
The page is called using the following function:
function imageZoom(imageName)
{
window.open('ImageZoom.htm?' + imageName + '','imageZoom','width=400,height=400,menubar=no,toobar=no,scrollbars=yes,resizable=yes');
}
Write the IMG tag dynamically using JavaScript during page load, and resize the window at onload:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Zoom</title>
<meta http-equiv="Pragma" content="no-cache" />
<script type="text/javascript">
function sizeWindow() {
//find the image control
var img = document.getElementById('dynamicImage');
//set the window to be just larger than the image
window.resizeTo(img.width + 50, img.height + 50);
}
</script>
</head>
<body onload="sizeWindow();">
<script type="text/javascript">
var filename = window.location.search.substring(1);
document.write("<img src='../Images/" + filename + "' id='dynamicImage' alt='Image Zoom' />");
</script>
</body>
</html>
You need to set the SRC of the <img> to something initially. If you don't desire to display anything, just use a 1x1 pixel transparent GIF.
have you tried bind the getImage function to the window's onload event rather then to the body's onload?

Categories

Resources