Changing source of img in js and get 0 for width?

Viewed 50

I am currently trying to set the source of an image HTML tag using jquery and then get the height and the width of the image. However, when trying to do so with the following code, the width I get is 0 and same with height :

$(document).ready(function() {
    
    $("#image").attr("src", "https://via.placeholder.com/600x160.png?text=Testing Image");
    console.log($("#image").width());
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
    <img id="image" />
</div>

I am trying to do this in order to change the image src of the same HTML tag and get the new width and height.

I found that it was due to the image not loaded in the DOM so I tried some things I found on internet as the two following snippets but with the same result of a width of 0 and a height of 0 :

$(document).ready(function() {
    
    $(`<img id='image' src='${"https://via.placeholder.com/600x160.png?text=Testing Image"}'>`).appendTo('#container');
    console.log($("#image").width());
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>

$(document).ready(function() {
    
    let image = new Image();
    image.src = "https://via.placeholder.com/600x160.png?text=Testing Image";
    image.id = "image";
    $('#container').append(image);
    console.log($("#image").width());
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>

I do not know if you can understand my needs, but I would really appreciate help there.

Thanks in advance.

2 Answers

You should use a load event, in order to wait until the image is loaded and has been shown up

see below snippet :

using Jquery :

$(document).ready(function() {
    var $image = $("#image");
    $image.attr("src", "https://via.placeholder.com/600x160.png?text=Testing Image");
    $image.on("load", function() {
        console.log($(this).width(),"X",$(this).height());
    })
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
    <img id="image" />
</div>

using pure js :

    let image = new Image();
    image.src = "https://via.placeholder.com/600x160.png?text=Testing Image";
    image.id = "image";
    
    image.addEventListener("load", function(event) {
      console.log(this.width ,"x",this.height)
    });
    
    let container = document.getElementById("container")
    
    container.appendChild(image);
<div id="container" ></div>

You need to listen image's onload event listener:

const img = new Image();

img.setAttribute('src', 'https://via.placeholder.com/150');
console.log('img width before load', img.width);

img.addEventListener('load', () => console.log('img width after load', img.width));

document.body.appendChild(img);

Related