Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2004
    Posts
    91
    Thanks
    0
    Thanked 0 Times in 0 Posts

    image's onload event behaves strangely

    Hello

    I am trying to provide a preview mechinsm for users who will upload images.
    This is what my code looks like:
    Code:
    <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:
    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

  • #2
    Senior Coder
    Join Date
    Aug 2002
    Location
    UK
    Posts
    2,789
    Thanks
    2
    Thanked 14 Times in 14 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •