Aleksandr Gvozdev
Aleksandr Gvozdev

Reputation: 95

How I get img height without append this image in DOM?

I have original image src in data-attr my element. I want get height this image. But I don't want append image to DOM. How I can get height? My code:

const imgSrc = $target
  .closest('.js-photo-item')
  .find('.photos__img--value')
  .data('original-image');
const $img = $(new Image()).attr('src', imgSrc);

console.log($img.height()) // this return 0

Upvotes: 0

Views: 42

Answers (2)

const imgSrc = $target
    .closest('.js-photo-item')
    .find('.photos__img--value')
    .data('original-image');
  const $img = $(new Image()).attr('src', imgSrc);

  $img.on('load', () => {
    console.log($img[0].height) // return height img
  });

Thanks George P user. His answer above...

Upvotes: 1

George
George

Reputation: 4257

You need to wait for the image to load first instead of trying to check the height right away. See, for example, https://stackoverflow.com/a/14134416/922613

Upvotes: 1

Related Questions