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.
2
The issue is that you are trying to read the height and width before the image loads. Because of that, you get the values as zero.
You need to wait until the image has loaded to be able to read the actual values. Adding an event listener for the load
event on the first image should fix the issue.
Something like this:
const img1 = document.getElementById("1");
img1.addEventListener("load", function() {
const w = img1.offsetWidth;
const h = img1.offsetHeight;
const img2= document.getElementById("2");
img2.style.width = w + 'px';
img2.style.height = h + 'px';
});
<img id='1' src='https://images.unsplash.com/photo-1725859685127-c723ea1d32a1?'>
<img id='2' src='https://images.unsplash.com/photo-1725859685127-c723ea1d32a1?'>
3