jon z
jon z

Reputation: 3

Find img height and write attribute - jquery

Trying to find the img height and apply inline as attr. Currently img only has src attr but want to dynamically find height and apply.

Current

  <img src="#">

Desired

<img src="#" height="find this images height">

This is what i have so far

$(document).ready(function() {
 $("img").load(function() {
 var width = $(this).width();
 var height = $(this).height() ;

 $(this).attr( "height", "+ height" );
 });
});

Any ideas?

Upvotes: 0

Views: 117

Answers (2)

airyt
airyt

Reputation: 352

A little unclear here whether or not you need the height of the image before you write to the DOM. here's how to get the width & height with straight javascript:

var img   = document.getElementById('image_id'); 
var img_w = img.clientWidth;
var img_h = img.clientHeight;

here's how to do it with jQuery:

var img   = $("<img src='image_url' />");
var img_w = img.width;
var img_h = img.height;

good luck...

answer appended:

var img_h; var img_w;
var img = new Image();
img.src = img_src;
img_h   = img.height;
img_w   = img.width;
document.write( "<img src=" + img_src + " height=" + img_h + " />" );

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382284

From jQuery documentation :

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

It doesn't work consistently nor reliably cross-browser

It doesn't fire correctly in WebKit if the image src is set to the same src as before

It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache

You may use this :

var img = $('img').get(0); // no better selector ?
if (img.height) alert('height is '+img.height);
else img.onload = function(){alert('height is '+img.height)};

In a cleaner way :

function onImgLoaded(img, callback) {
   if (img.width) callback(img));
   else img.onload = function(){callback(img)};
}
onImgLoaded($('img').get(0), function(img){
    alert('height is '+img.height);
});

Upvotes: 1

Related Questions