3

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();
j08691
  • 204,283
  • 31
  • 260
  • 272
DCR
  • 14,737
  • 12
  • 52
  • 115

1 Answers1

2

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();
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • isn't better to set the `onload` listener before setting `src` of the dynamically created image? As stated here: https://stackoverflow.com/a/12355031/8732818 – Calvin Nunes Feb 24 '20 at 19:35