-4

How to get real image width & height (cross browser) by JavaScript function ?

1
  • 3
    "as the title" is unacceptable text, you are asking others to take sometime to answer your question, do the curtesy of taking some time to ask your question. Commented Jan 13, 2009 at 15:36

4 Answers 4

10

First of all, you have a greater chance of getting your question answered if you'd just ask it in a more polite way, and supplying as much relevant information as possible.

Anyway...

For as far as I know, you can use the .width property across pretty much all browsers:

function getDimensions(id) {
    var element = document.getElementById(id);
    if (element && element.tagName.toLowerCase() == 'img') {
        return {
            width: element.width,
            height: element.height
        };
    }
}

<img id="myimage" src="foo.jpg" alt="" />

// using the function on the above image:
var dims = getDimensions('myimage');
alert(dims.width); --> shows width
alert(dims.height); --> shows height
Sign up to request clarification or add additional context in comments.

1 Comment

height misreports in IE11
8
var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");

1 Comment

where is the documentation for this?
4

Yay, Google!

There's a few ways to do this depending on exactly what you need (which you have unhelpfully omitted to include). Probably the simplest in a general sense is to get a reference to the Image object and inspect the width and height properties.

3 Comments

I like to give this to people when it's obvious they did not google: letmegooglethatforyou.com/?q=javascript+image+width+height
For me, this very page is the result of that Google search today.
I can assure you it wasn't when I posted this two-and-a-half years ago. :)
0

jquery + <img src="" ... id="hello" /> + $("#hello").width()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.