1

I have multiple images on a page and this code:

//main image
<img src="/my_image.png" id="main_img" />

//other images
<img .... onclick="setMainImg(this)" />



<button onclick="getSize()">get size</button>



//js, at the bottom
var mainImg = document.getElementById("main_img");

function getSize() {
  console.log(mainImg.width + "x" + mainImg.height + "\r\n");
}

When the page loads, it prints something like 33x16

After I click on different images:

  //js
  function setMainImg(img) {
    mainImg.src = img.src;
  }

it begins printing the corrent values in the console:

448x354

and something like this. Even when I click the same first image(!), it prints a different, 10 times bigger, size.

Why? How to fix this?

hohaf
  • 21
  • 1
  • 3

1 Answers1

0

You have to get size after image loading, so you should set variable of your image whenever you click.

var mainImg;

function getSize() {
  mainImg = document.getElementById("main_img");
  console.log(mainImg.width + "x" + mainImg.height + "\r\n");
}
Ibra
  • 906
  • 1
  • 7
  • 13
  • how will that ensure that "after image loading" has happened? – hohaf Apr 04 '19 at 05:20
  • @hohaf https://stackoverflow.com/questions/280049/how-to-create-a-javascript-callback-for-knowing-when-an-image-is-loaded – Ibra Apr 04 '19 at 05:23