Tuesday, April 12, 2011

Get image width & height with Javascript

Ever needed to get the real dimensions of an image with javascript that works on all browsers, even when the width and height hasn't been explicitly set (either on the img tag or with css) ? Here's how to do it

Include JQuery on your page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>

Give your image an explicit id:

<img id="someId" src="mypicture.jpg" />

Use this JQuery snippet to get the width and height:

// Our vars holding the width and height
var pic_width, pic_height;

// Load an image into memory, to prevent any css affecting it
var img = $('<img />');

// Bind the image to an onload event
img.bind('load', function() {
  pic_width = this.width;
  pic_height = this.height;
});

// Load the image, onload will fire and store width and height
$(img).attr('src', $('#someId).attr('src'));

The onload event needs to be bound before loading the actual image to make sure it fires.

No comments:

Post a Comment