JavaScript only works when page is reloaded - javascript

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?

Related

My JavaScript program doesn't reload picture as quickly as I want

So I have the following problem: I want my JavaScript to reload an image from my desktop so quickly that the picture in the browser changes as soon as I change/edit the picture on my desktop. It works as intended for maybe the first two times, but then I have to wait a couple of seconds before the picture on my browser changes to the new picture I have on my desktop.
As it's using the same URL, I have a cache breaker so that the browser always loads the new image and I specified at the top as a header that the cache shouldn't store the image, so the browser always checks the image on my desktop. What am I doing wrong? Why isn't it working as intended?
<html>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<head>
<title>JavaScript Refresh Example</title>
</head>
<body>
<canvas id="canvas" width="2000" height="2000"/>
<script type="text/JavaScript">
var img = new Image();
var time = new Date();
function draw() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
}
function refreshImage() {
var timestamp = new Date().getTime();
var queryString = "?t=" + timestamp;
return "Bild1.jpg" + queryString;
}
function Animate() {
window.requestAnimationFrame(Animate);
draw();
img.src = refreshImage();
}
img.onload = function () {
Animate();
}
img.src = refreshImage();
</script>
</body>
</html>

canvas element has extra wide upper border

why my page has a lot of empty space between buttons and canvas. when I upload some image
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>uploader</TITLE>
</HEAD>
<body>
<input type="file" name="img" id="uploadimage" size="1">
<a id="downloadLnk" download="img.jpg">download</a>
</p>
</td>
<script>
function draw() { //upload
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.zURL || window.URL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
var parkBg = new Image(600, 500);
document.body.appendChild(parkBg);
parkBg.src = src;
}
}
function download() { //upload
var dt = canvas.toDataURL('image/jpeg');
this.href = dt;
};
downloadLnk.addEventListener('click', download, false);
document.getElementById("uploadimage").addEventListener("change", draw, false)
</script>
<canvas id="canvas"></canvas>
</body>
</html>
The empty space you are seeing is in fact canvas element - without CSS styling it is invisible.
You are not displaying image on canvas - You are adding image element to the document and in it displaying uploaded image.
I suspect You need to display image on canvas.
See my example that accomplishes exactly that: https://jsfiddle.net/hxfp39wo/1/

Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery?

So I'm trying to do some very basic div re-sizing based on the properties of the image contained within it. I know I can do something really basic like set the background an padding around the image and achieve the same effect, but this is sort of a personal challenge.
The problem I am having is that when I try to fetch the naturalHeight or naturalWidth values of the image, I get a value of 0. However, when I try to fetch these values using the console, they return the correct values. Also, my resizeDiv() function is coming up as undefined in console.
Here's the code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>kitten_resize - WesGilleland.com</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var kittens = new Array("100x100_kitten.jpeg","150x150_kitten.jpeg","200x150_kitten.jpeg");
$('#kittens').attr('src', kittens[0]); //set the image
function resizeDiv() {
var img = document.getElementById('kittens');
var imgH = img.naturalHeight;
var imgW = img.naturalWidth;
$('div').width(imgW);
$('div').height(imgH);
console.log('Current imgH: '+imgH);
console.log('Current imgW: '+imgW);
};
resizeDiv();
});
</script>
<style>
div {
background-color: black;
padding: 10px;
margin: auto;
}
</style>
</head>
<body>
<div>
<img id="kittens" src='' />
</div>
</body>
</html>
You can also find a working copy here: http://www.wesgilleland.com/projects/kitten_resize/
I feel like it's something very basic that I'm missing; I haven't fiddled with this stuff since my associate's degree a year ago. Thanks to anyone who can help!
That's because your image isn't yet loaded when you read the original dimensions.
You should read the dimensions when the image is loaded :
var img = $('#kittens')[0];
img.onload = resizeDiv;
img.src = kittens[0];

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 getElementById(...) is null or not an object IE

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;
};

Categories

Resources