Skip to content Skip to sidebar Skip to footer

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 orientat

Solution 1:

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

Solution 2:

You cannot use condition with else part of if-else statement. Use the following code structure:

img.onload = function () {
  if (condition) {
     // if above condition is true then do this ...
  } else {
    // otherwise do this ...
  }
});

var images = $('.img img');

images.load(function() {
  if (this.naturalWidth > this.naturalHeight) {
    $(this).addClass('landscape');
  } else {
    $(this).addClass('portrait');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img">
  <img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Image Description">
</div>

Post a Comment for "Add Different Classes To VERTICAL Or HORIZONTAL Img"