Andresaurus
Andresaurus

Reputation: 7

Add css to all img with same class with jQuery

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.

Upvotes: 0

Views: 220

Answers (3)

user8914070
user8914070

Reputation:

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 );
});

Upvotes: 0

ethancrist
ethancrist

Reputation: 114

function cropImg() {
    $('.prodImg').each(function() {
        var isWider = $(this).outerWidth() > $(this).outerHeight();
        isWider ? $(this).css({'max-height':'100%'}) : $(this).css({'max-width':'100%'})
    })
}

Upvotes: 0

wpcoder
wpcoder

Reputation: 1054

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.

Upvotes: 1

Related Questions