views:

1041

answers:

3

I'm trying to set the width & height property of an image element i've created in javascript. In FF, Opera & Chrome it's sets the width & height correctly. However in IE 6 & 7 (Haven't tried 8) the width & height remain 0 until the image is downloaded. The reason I need this is so that i can position each image in rows & cols based on it's current size.

If it's not possible to set the width & height properties in IE I think i'll just have to create my own custom property and set it in there.

Here is the basic code i'm using to create & inject the element.

var img = document.createElement('img');
var wrap = document.createElement('div');

document.body.appendChild(wrap);
wrap.appendChild(img);

img.src = 'blah.jpg';
img.width = '100';
img.height = '100';
img.style.display = 'none';

// IE: width: 0 | height: 0
// FF: width: 100 | height: 100
alert('width: ' + img.width + ' | height: ' + img.height);

EDIT:

I've tried setting img.style.visibility = 'hidden' instead of img.style.display='none'; but it doesn't make a difference.

EDIT

I found the issue. The actual problem was a combination of Aziz solution and something I left out in the original example. It appears that in IE if you append the element inside another element before assigning a width & height IE just ignores it.

+2  A: 

This problem is explained here

In order to get the correct dimensions in IE, you need to set display: hidden visibility: hidden. However, you have to make sure you set it only if the browser is IE.

Edit try this (works with me)

var img = document.createElement('img');

img.src = 'blah.jpg';
img.width = '3000';
img.height = '1000';

img.style.visibility = 'hidden';


document.body.appendChild(img);

// should work correctly
alert('width: ' + img.width + ' | height: ' + img.height);
Aziz
+1  A: 

You will need the unit:

var img = document.createElement('img');

img.src = 'blah.jpg';
img.style.display = 'none';
img.style.width = '100px';
img.style.height = '100px';

document.body.appendChild(img);

// IE: width: 0 | height: 0
// FF: width: 100 | height: 100
alert('width: ' + img.style.width + ' | height: ' + img.style.height);

Use element.style.width and element.style.height instead of element.width and element.height respectively for cross browser compatibility. Also remember to add the unit "px".

thephpdeveloper
A: 

i am not able to find image width and height while uploading the image in ie but firefox its working fine.....

Nagendra