Federico Ferrari Federico Ferrari - 4 months ago 11
CSS Question

Add different classes to VERTICAL or HORIZONTAL img

I want to style differently the images if they are vertical or hotizontal.

I'm playing around with this code but it's not working. Any ideas?

JAVASCRIPT

(function() {

var orientation,
img = new Image();

img.onload = function () {

if (img.naturalWidth > img.naturalHeight) {
$(img).addClass('landscape');}

else (img.naturalWidth < img.naturalHeight) {
$(img).addClass('portrait');}

})();


CSS

img {max-width:500px;}
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}

Answer

I've just created short codepen here to show you my way of working with images: codepen link

HTML:

<img src="https://pixabay.com/static/uploads/photo/2014/07/27/20/29/landscape-403165_960_720.jpg" />

<img src="https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg" />

CSS:

.landscape {max-width: 750px;}
.portrait {max-width: 500px;}

JS:

window.onload = function () {
  var images = document.getElementsByTagName('img');

  for( var i=0; i<images.length;i++){
    if (images[i].naturalWidth > images[i].naturalHeight) {
      $(images[i]).addClass('landscape');
    } 
    else{ 
      if(images[i].naturalWidth < images[i].naturalHeight) {
        $(images[i]).addClass('portrait');  
      }
    }
  }
}