Get size of an unknown image and change class

98 views Asked by At

On my Tumblr Theme I want to use a different CSS class for portrait images. Images, by default, come in via img-tag and get's the class bilder. But if it's an portrait image, I would like to replace the builder class with the hhcoch class.

HTML:

<img src="{..}" />

JavaScript:

    var someImg = $("img");
    if (someImg.height() > someImg.width()){
        $( "img" ).addClass( "hhoch" );
    }

CSS:

.bilder {
    height: auto; /*override the width below*/
    min-width: 100%;
    max-width: 100%;
    display: inline;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
}

.hhoch {
    min-height: 800px;
    max-height: 800px;
    width: auto;
}

Sum up: The image should get a different class if it's portrait.

2

There are 2 answers

10
Danny Delott On BEST ANSWER

You've got the right idea, however that specific jQuery selector you're using is going to return an array of ALL the image tags in your document.

This means you'll want to loop over the array of image DOM nodes and apply your class that way.

 var $images = $('.bilder');
 $images.each(function(index, img){
   if(img.height > img.width){  // is it a portrait-image?
     $(img).removeClass('bilder');  // Remove default class
     $(img).addClass('hhoch');  // Add the portrait class
   }
 });
0
Ally On

Have you tried condensing the solution to this:

$("img.bilder").each(function(){
  if (this.height > this.width) {
      $(this).removeClass("bilder").addClass("hhoch");
  }
});

Because I don't think all those extra lines of code are needed and might be your problem. As others were saying, it will return an array of objects so you need to loop through them all.