View Full Version : image's onload event behaves strangely

07-07-2004, 06:19 PM

I am trying to provide a preview mechinsm for users who will upload images.
This is what my code looks like:

<img id="image" src="placeholder.gif" width="100" height="100" onload="setImageDimensions(this);"></img>
<input type="file" name="imageLoader" id="imageLoader" onchange="displayPreview(this)">

here is my JavaScript code:

function displayPreview(fileObj) {
document.getElementById("image").src = fileObj.value;

function setImageDimensions(imageElement) {
// set the width and height of the new image...

The problem is that sometimes the onload event gets fired and sometimes it doesn't. I am not sure why.
The displayPreview function gets called everytime so the onchange event is working correctly.

In times when the onload event is not triggered and thus setImageDimensions is not called, the newly loaded image is displayed using the dimensions of the previous loaded images (or the placeholder if it happens on the first upload) which may cause the image to become distorted.

help is appreciated

Mr J
07-07-2004, 09:07 PM
If the uploaded images are going to vary in size then take out the width and height attributes from the image tag, this may help