Getting Image height before the image loads in HTML

17,589

Solution 1

If you are trying to dynamically resize a couple of divs in a row within a table, you maybe better off using a html table instead and having each image within a td tag. This will make tr tag resize accordingly for the image in each cell.

Solution 2

  this.img = new Image();
  this.img.src = url;
  alert(this.img.width);

gives the width while

  var img = new Image();
  img.src = url;
  alert(img.width);

doesnt..

dunno why.

Solution 3

You can:

  1. Not specify the height of the div, and let it expand automatically
  2. Once the image is loaded do:

    document.getElementById("myDiv").height = document.getElementById("myImage").height

Share:
17,589

Related videos on Youtube

niton
Author by

niton

Add Option Explicit to the top of your VBA code. Remove unused variables and declare the rest. https://excelmacromastery.com/vba-error-handling / "On Error Resume Next , is the most commonly used and misused form. It instructs to VBA to essentially ignore the error and resume execution on the next line of code. It is very important to remember that On Error Resume Next does not in any way "fix" the error." http://www.cpearson.com/excel/errorhandling.htm

Updated on April 17, 2022

Comments

  • niton
    niton about 2 years

    I have a table that is dynamically created using DIVs. Each row of the table has two images. I want to set the height for the div (that represents a particular row) to the height of image that is greater of the two images being displayed in that particular row. The images to displayed will always change, and they are from an external server.

    How do I set the height for my div so that I can fit images?

  • Admin
    Admin over 15 years
    the table has lot of rows. won't this make the UI look bad?
  • Admin
    Admin over 15 years
    how do I connect these image objects with respective div tags that are supposed to display them?
  • Kornel
    Kornel over 15 years
    width and height are 0 immediately after creating image. You have to wait for image to fire load event before checking its size.
  • henry bemis
    henry bemis over 11 years
    Thanks! This answer is surprisingly hard to find. I actually used the second one, and it works great.
  • Abbafei
    Abbafei over 10 years
    The reason why, as far as I know, is because the image has not necessarily finished loading yet (I suppose it loads asynchronously).