1
votes

I need to get width and height for an image which is being loaded from an API, no css will be applied to the image. Image could have variable size depend on what loaded in the API/

At the moment using jquery or vanilla js I get always 0 for width and height?

What is the problem in my code? Should I set dynamically width and height when creating the img tag? How to do it?

   this.getItemSize = function() {
        var elm = $('#' + scope.elmItem);
        var pos = elm.offset();

        /* also with this vanila js does not work
        var image = document.getElementById(scope.elmItem);
        console.log(image);
        var width = image.offsetWidth;
        var height = image.offsetHeight;
        */

        scope.itemTop = pos.top;
        scope.itemLeft = pos.left;
        scope.itemWidth = elm.width();
        scope.itemHeight = elm.height();
        console.log(scope.itemTop + " " + scope.itemLeft + " " + scope.itemWidth + " " + scope.itemHeight);
    };



            $.get(this.url, function(image) {
                // add img to the dom
                var img = $('<img id="item">');
                img.attr('src', scope.url);
                img.appendTo('#' + scope.elm);

                scope.getItemSize();
            });
1
Thanks Alex for your edit :-)GibboK

1 Answers

0
votes

You need to call getItemSize after the image is loaded, you can use the .load() event handler to do this

$.get(this.url, function(image) {
    // add img to the dom
    var img = $('<img id="item">');
    img.load(function(){
        scope.getItemSize();
    })
    img.attr('src', scope.url);
    img.appendTo('#' + scope.elm);