DCR
DCR

Reputation: 15665

getBoundingClientRect() returns 0 for width and height of image

Ho do I use getBoundingClientRect() to determine the width and height of image

function popUp() {
  var img = document.createElement('img');
  img.id = "TT";
  img.src = "https://picsum.photos/200/300";
  document.body.appendChild(img);
  var img = document.getElementById("TT");
  console.log(img)
  var dims = img.getBoundingClientRect();
  console.log(dims)
}
popUp();

Upvotes: 3

Views: 5463

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

This is because the image is not loaded at the time of log. You need to console.log inside onload function

function popUp() {
  var img = document.createElement('img');
  img.id="TT";
  img.src="https://picsum.photos/200/300";    
  document.body.appendChild(img);
  img.onload = function(){
    var img = document.getElementById("TT");
    var dims = img.getBoundingClientRect();
    console.log(dims)
  }
}
popUp();

If you want the function to await for further execution of the function until the image is loaded you can create a promise and then await for it. But this will make the structure of the code asynchronous

async function popUp() {
  var img = document.createElement('img');
  img.id="TT";
  img.src="https://picsum.photos/200/300";    
  document.body.appendChild(img);
  const imageLoaded = new Promise((res, rej) => {
    img.onload = function(){
      var img = document.getElementById("TT");
      var dims = img.getBoundingClientRect();
      res(dims)
    }
  });
  
  const data = await imageLoaded;
  console.log(data)
	
}
popUp();

Upvotes: 2

Related Questions