getting picture width and height in javascript

Discussion in 'HTML & Website Design' started by Benjamins, Aug 30, 2009.

  1. #1
    Hi all,

    I (beginner) would like to show the original size of a picture.
    I tried that:

    HEAD:
    <script type="text/javascript">
    pic1 = new Image();
    pic1.src = "img/C ... jpg"
    var breite1 = document.pic1.width
    var hoehe1 = document.pic1.height
    </script>

    BODY:
    <script type="text/javascript">
    document.write(breite1)
    document.write(hoehe1)
    </script>

    What it shows is: "undefined"

    Where is the error ??
     
    Benjamins, Aug 30, 2009 IP
  2. Benjamins

    Benjamins Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    anyone, please?
     
    Benjamins, Aug 30, 2009 IP
  3. FilmFiddler

    FilmFiddler Greenhorn

    Messages:
    54
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    23
    #3
    It's undefined because the image has not actually loaded yet in the above code. Try this:


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Test</title>
    <script type="text/javascript">
    function loadImage() {
      pic1 = new Image();
      pic1.onload = function() {
        var w = pic1.width;
        var h = pic1.height;
        document.getElementById("img_width").innerHTML += w + " px";
        document.getElementById("img_height").innerHTML += h + " px";
      };
      pic1.src = "images/my_image.jpg"; // ... add image URL here
    }
    </script>
    </head>
    <body>
    <div>
      <p id="img_width">Image width is:&nbsp;</p>
      <p id="img_height">Image height is:&nbsp;</p>
      <input type="button" onclick="loadImage()" value="Show Image Width">
    </div>
    </body>
    </html>
    Code (markup):
     
    FilmFiddler, Aug 31, 2009 IP
  4. Hemuro

    Hemuro Peon

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    do this
    HEAD:
    <script type="text/javascript">
    pic1 = new Image();
    pic1.src = "img/C ... jpg";
    var breite1 = document.pic1.width;
    var hoehe1 = document.pic1.height;
    </script>

    BODY:
    <script type="text/javascript">
    document.write(breite1);
    document.write(hoehe1);
    </script>
    you forgot semicolons. common beginner mistake.

    or just do
    <script language="javascript">
    document.write("<img src"source"/ >);
    </script>
    if you must use javascipt.
     
    Hemuro, Aug 31, 2009 IP