Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the width and height of a dynamic loaded image in javascript?

I am displaying a few images dynamically from javascript. I need to get the image height and width. I am using "naturalWidth" and "naturalHeight" to get width and height. The first time I am loading I am getting height and width but after a few minutes, I am getting 0.

HTML:-

<div class="col-md-8" id="view_port_img" style="text-align: center;">
</div>

JAVASCRIPT

let img_div = 
    <img id="view_img_0" class="pointer micro_otpt view_port_img" src="https://picsum.photos/id/877/200/300" alt="user"></img>; 
    $('#view_port_img').html(img_div);
    var myImg = document.querySelector("#view_img_0");
    var imgWidth = myImg.naturalWidth;
    var imgHeight = myImg.naturalHeight;

In the first load, I am getting height and width but after a few mins, I am getting 0. Does anyone have any solution for this?

like image 432
Sweta Sharma Avatar asked Feb 02 '26 09:02

Sweta Sharma


1 Answers

Actually you are trying to get the image size of the image which has not been loaded yet in the DOM.You have to check whether the image is loaded on DOM or not ,by either image on load function or document ready. Try this

//var myImg = document.querySelector("#view_img_0");
function append_image() {

  let img_div =
    '<img id="view_img_0" class="pointer micro_otpt view_port_img" src="https://picsum.photos/id/877/200/300" alt="user">';
  $('#view_port_img').html(img_div);

}
append_image();

$(document).ready(function() {

// Your way
var myImg = document.querySelector("#view_img_0");
    var imgWidth = myImg.naturalWidth;
    var imgHeight = myImg.naturalHeight;
    console.log(imgWidth);
     console.log(imgHeight);
     
     //This also works
  console.log($('#view_img_0').width())
  console.log($('#view_img_0').height())

})

// Detect IF Image is loaded

$("#view_img_0")
    .on('load', function() { console.log("On Load",$('#view_img_0').width()); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-8" id="view_port_img" style="text-align: center;">
</div>
like image 54
Shubh Avatar answered Feb 05 '26 00:02

Shubh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!