Q:

How to resize image to fit DIV jQuery

I have square DIV and large portrait and landscape images.
I need to fit the image in a DIV with the extra part going overflow:hidden
For eg. If portrait set width=width of div height:auto
Opposite for Lanscape.
I tried this script but it didn;t work
        $('.magic').each(function(){
        if($(this).css('width')>$(this).css('height')){
            $(this).css('height', '300px');
            $(this).css('width', 'auto');                
        }
        else{
            $(this).css('width', '300px');
            $(this).css('height', 'auto');

        }
    });

PS Images can't stretch and must scale

A:

Use some CSS like this
.magic.portrait {
    height: 300px;
    width: auto;
}

.magic.landscape {
    width: 300px;
    height: auto;
}

and just add a class with your JS
$('.magic').each(function(){
    if($(this).width() > $(this).height()){
        $(this).addClass('landscape');
    }else{
        $(this).addClass('portrait');
    }
});

This also helps keep your application logic and styles nicely separated. Even better, add these classes server side, and avoid the JavaScript altogether.

