0

I have 4 divs with images inside them and I need to add a class property depending on the img width and height.

Here's an example code to explain what I need to do. (Obviously, this code doesn't work)

function cropImg(){
  var imgs = document.getElementsByClassName(".prodImg");
  for(i in imgs){   
    var imgWidth = imgs[i].naturalWidth;
    var imgHeight = imgs[i].naturalHeight;

    if(imgWidth>imgHeight){
      imgs[i].css({
        "max-height": "100%"
      });
    }else{
      imgs[i].css({
        "max-width": "100%"
      });
    }   
  }
}

I really appreciate your help.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • please add some html from divs, and your function look like resizing image , not cropping it, can you please clarify what you need exactly? – wpcoder Nov 12 '17 at 02:43

3 Answers3

1

It's not the best practice or optimal solution; just something simple to start with and tweak.

$(function () {

    cropImg();

    function cropImg() {

        var imgs = $(".prodImg");
        imgs.each(function (index, element) {
            var imgWidth = $(this).width();
            var imgHeight = $(this).height();
            if (imgWidth > imgHeight)
                $(this).css({
                    "height": "100%",
                    "width": "auto"
                });
            else
                $(this).css({
                    "width": "100%",
                    "height": "auto"
                });

        });

    }

});

To properly crop and resize images and keep aspect ratio; check this demo.

Or this stack answer.

wpcoder
  • 1,016
  • 11
  • 17
0

jQuery .each() is your friend

The problem in determining the true size of an image is that it can be resized on the pages of a site. And the jquery functions only give the dimmensions present on the browser and not their actual size.

For my solution I propose precisely to force the dimmensionnement of the images to their real size to know the values of them to replace the initial values then.

PS: width or heigth at 100%, does'nt work any time, because it give the size of the parent element, whitch is rarely the real size.

I tested this code before, but it is possible that some constraints in the hierarchy css can put his grain of sand.

$("div img").each(function( index ) {
    var
    sav_h = $(this).height(),
    sav_w = $(this).width(),
    real_h = 0,
    real_w = 0;

    $(this).css({width:'auto', height:'auto'});

    real_h = $(this).height(),
    real_w = $(this).width();

    $(this).height(sav_h).width(sav_w);
    console.log( index + "       h=" + real_h + '     w=' + real_w );
});
0
function cropImg() {
    $('.prodImg').each(function() {
        var isWider = $(this).outerWidth() > $(this).outerHeight();
        isWider ? $(this).css({'max-height':'100%'}) : $(this).css({'max-width':'100%'})
    })
}
ethancrist
  • 114
  • 7