1

I'm trying to get the width and height of a div after it finishes loading by using javascript, but it's getting the width and height of the div BEFORE the image finishes loading. What can I do to fix this?

<script type = "text/javascript">
var width = document.getElementById("image").offsetWidth;
var height = document.getElementById("image").offsetHeight;
alert(width+":"+height);
</script>
#image {
border: 1px solid red;
width: 50%;
}
<div id = 'image'>
<img src = 'http://exmoorpet.com/wp-content/uploads/2012/08/cat.png'>
</div>

Result:

634:2

Expected Result:

634:(More Than 2 Pixels)
LOTUSMS
  • 10,317
  • 15
  • 71
  • 140
frosty
  • 2,559
  • 8
  • 37
  • 73

2 Answers2

2

Use .load to wait till that element is loaded in the dom

$("#image").load(function() {
  var width = document.getElementById("image").offsetWidth;
  var height = document.getElementById("image").offsetHeight;
  alert(width+":"+height);
});
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32
0

here is a javascript snippet

Note: Your width is 50% so depends on the size of the window, your div width will change.hence you wouldn't obtain a fixed width unless you use an absolute unit of measurement

var width=height=null;
function handler(){
width=document.getElementById('image').offsetWidth;
height=document.getElementById('image').offsetHeight;
alert('width:'+width+',height: '+height);
}
document.getElementById('actual_image').addEventListener('load',handler,false);
#image {
border: 1px solid red;
width: 50%;
}
<div id = 'image'>
<img id="actual_image" src = 'http://exmoorpet.com/wp-content/uploads/2012/08/cat.png'>
</div>
repzero
  • 8,254
  • 2
  • 18
  • 40