0

I'm appending an image with jQuery and i can't get the sizes (width and height) of it.

Here it is the HTML code:

<input type="checkbox" id="RocketElement" data-id="1">

Here it it is the JS/jQuery code:

$(document).ready(function() {

        function printOne(newData) {
            var deferred = $.Deferred();

            $("#Images").append("<img data-id='" + newData.attr("data-id") + "' src='file:///C:/Users/David/Documents/test/" + newData.attr("data-id") + ".png'>");

            deferred.resolve();

            return deferred.promise();
        }

        function getSizes(newData) {
            console.log($("img[data-id='" + newData.attr("data-id") + "']").width());
        }

        $("input#RocketElement").on("change", function() {
            Data = $(this);
            printOne(Data).done(function() {
                getSizes(Data);
            });
        });

    });

However, when i add a delay after the .append of 10ms it works. Is there any way to wait until the DOM has been updated and then continue with the execution of the code?

Weyooo
  • 26
  • 1
  • 7
  • using a mutation observer might work for you: https://stackoverflow.com/a/11546242/1291935 – DrCord Jul 12 '19 at 22:08
  • Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Jul 13 '19 at 01:26

1 Answers1

0

Not sure what you want to do but you can always pass in a callback function.

$(function() {

  function printOne(obj, cb) {
    var newImage = $("<img>", {
      src: "https://i.imgur.com/" + obj.data("id") + ".jpg",
      class: "appended"
    }).data("ref-id", obj.data("id")).appendTo($("#images"));
    cb();
  }

  function getSizes() {
    $("#images img").each(function(i, el) {
      console.log($(el).data("ref-id") + ": " + $(el).css("width"));
    });
  }

  $("input#RocketElement").on("change", function() {
    printOne($(this), getSizes);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="RocketElement" data-id="aMaSED2">
<div id="images"></div>

I have seen that .width() doesn't do too well all the time. Getting the CSS Width is often more effective.

Hope that helps.

Twisty
  • 30,304
  • 2
  • 26
  • 45