drake035
drake035

Reputation: 2877

Is it possible to get the actual width of an image contained in a div smaller that it?

Let's say I have an image whose actual width is 1000px, but its width in CSS is set as 100% and it is contained in a 500px wide div.

Is there a way for jQuery to know that the image is actually 1000px wide even though its width on the page is only 500px?

Upvotes: 1

Views: 21

Answers (2)

David Thomas
David Thomas

Reputation: 253318

Yes, using naturalWidth:

var realWidth = imgElement.naturalWidth;

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074258

What you can do is create a new image with the same src off-page, and measure that.

For instance, if your existing img element has the id "foo", then:

$("<img>")
    .css({
         position: "absolute",
         left: -10000,
         top: 0
    })
    .on("load", function() {
        var realWidth = this.width;
        var realHeight = this.height;
        $(this).remove();

        // Use `realWidth` and `realHeight` here
    })
    .appendTo(document.body)
    .attr("src", $("#foo").attr("src"));

Upvotes: 0

Related Questions