I have two image tags displayed in a webpage, which may have different size. And since the images are dynamically generated, the size of both images may be different at each loading. I want to adjust the second image to have the same size as the first image. Here is what I have tried:
<img id='1' src='img1.jpg'>
<img id='2' src='img2.jpg'>
<script>
const img1 = document.getElementById("1");
const w = img1.offsetWidth;
const h = img1.offsetHeight;
const img2= document.getElementById("2");
img2.style.width = w + 'px';
img2.style.height = h + 'px';
</script>
What I found is that occasionally the width and height are read as 0, which may be caused by the script ran before the first image was loaded. I am thinking to put an onload()
function to the first image, however, I think in case if image2 is not loaded when onload
is fired, then it won’t be adjusted.
Also, if the browser is somehow running slow, such size change maybe sensible by the user. What’s a more efficient and reliable way to make two images displayed with the same size at the first place? Note I don’t want to put them both into a div with fixed size, I only want the 2nd image to have the same size as the 1st one.