0

I want to be able to use jQuery to get the height / width of multiple images before the images are fully loaded into the page. I then need to set the height and margin of a image based on the the image width and height which is being loaded.

$(".review-content .photos .img").each(function() {
    if (!$(this).hasClass("showimg")) {
        var tarObj = $(this),
            imgsrc = $(this).find("img"),
            blockWid = tarObj.width(),
            blockHei = tarObj.height(),
            imgWid = imgsrc.width(),
            imgHei = imgsrc.height(),
            tarImg = tarObj.find("img"),
            formatHei = blockWid * imgHei / imgWid;
        if (formatHei > blockHei) {
            tarImg.css("width", blockWid + "px");
            var marHei = -(formatHei - blockHei) / 2;
            tarImg.css("margin-top", marHei + "px")
        } else {
            tarImg.css("height", blockHei + "px");
            var formatWid = blockHei * imgWid / imgHei,
                marWid = -(formatWid - blockWid) / 2;
            tarImg.css("margin-left", marWid + "px")
        }
        tarObj.addClass("showimg")
        tarImg.attr("data-width", imgWid)
        tarImg.attr("data-height", imgHei)
    }
})

Now the issue in above code is even if i add

$(".review-content .photos .img img").load(function() {

Before each function it will apply the calculations on some of the images and rest of the images will be messed up so someone please guide me in the right direction on how i can get the width and height of each image and apply the css accordingly to every image in the page

  • 1
    The width and height of the image are unknowable until the image is loaded. There are many ways to set a fixed container size or aspect ratio using CSS. – Mark Sep 03 '19 at 09:03
  • Yes but how can i force it to wait until the image is loaded and after that it can do the calculations because i have a loading icon in the place which is removed after the showimg class is added. – Harry Callum Sep 03 '19 at 09:05
  • Use a fixed size image container with something like `{ object-fit: cover }`. – Mark Sep 03 '19 at 09:11

1 Answers1

0

From comments:

how can i force it to wait until the image is loaded and after that it can do the calculations...

You could use the load event on each images.

$(".myImg").on("load",function(){
  var width=$(this).width();
  var height=$(this).height();
  console.log(width+" × "+height);

  // Use the width and height here...
});
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64