Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize image to fit DIV jQuery

Tags:

html

jquery

web

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

like image 505
cjds Avatar asked Nov 17 '25 10:11

cjds


1 Answers

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.

like image 103
DigitalDesignDj Avatar answered Nov 20 '25 00:11

DigitalDesignDj