0

On my website I have a page named "images", where I can display some images dynamically. But as each image is not the same size, I use jQuery to apply a class that resizes the image by the height or width, as this code:

JQUERY

$("img").each(function(){
    var widthImage = $(this).width();
    var heightImage = $(this).height();

    if(widthImage > heightImage){
        $(this).addClass('maxWidth');
        $(this).removeClass('maxHeight');
    }       
    else if(widthImage < heightImage){
        $(this).removeClass('maxWidth');
        $(this).addClass('maxHeight');          
    }
    else if(widthImage == heightImage){
        $(this).removeClass('maxWidth');
        $(this).addClass('maxHeight');
    }
});

CSS

.maxWidth{width: 100%;}
.maxHeight{height: 100%;}

The code works, but when I visit the page for the first time, the class "maxHeight" is applied to all images. Then, once you reload the page, the classes are in the right place.

Image before reload:

enter image description here

Image after reload:

AFTER

enter image description here

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    You can do it with CSS alone: http://stackoverflow.com/questions/12991351/css-force-image-resize-and-keep-aspect-ratio – iCollect.it Ltd Jul 11 '14 at 16:01
  • 1
    Have you put your script within `$(document).ready(function(){});` - if not, do that. – faerin Jul 11 '14 at 16:02
  • 1
    The problem is that the script is running before the images are loaded and so it has wrong values for the images height. Put your script inside a $(window).load() function or do it with css as suggested by TrueBlueAussie – Jonas Grumann Jul 11 '14 at 16:12

0 Answers0