KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2178

How to resize image using jquery

I have multiple images which I want to resize to a fixed height and the width will be resized in the ratio of the resized height and i want to achieve this using jQuery. So I gave all the images the same class attribute and I ran this code:

<img src="img1.jpg" class="imgs">
<img src="img2.jpg" class="imgs">
<img src="img3.jpg" class="imgs">
<script>
$(document).ready(function(){
    $('.imgs').each(function(){
        oldH = $(this).naturalHeight;
        oldW = $(this).naturalWidth;
        divH = "500px";
        if(oldH > divH){
            newH = divH;
            calW = newH / oldH;
            newW = calW * oldW;
            $(this).naturalHeight = newH;
            $(this).naturalWidth = newW;
        } else{
            newH = oldH;
            newW = oldW;
            $(this).naturalHeight = newH;
            $(this).naturalWidth = newW;
        } 
    })  
});
</script>

But the images are not resizing, I am still new to jQuery so I am not to good. I don't know if that's the right approach to achieve this. Please if it's not I need a clue on how to achieve this.

Upvotes: 0

Views: 282

Answers (3)

Dezefy
Dezefy

Reputation: 2096

$(this).naturalHeight; will not work. Because naturalHeight is not a jQuery function.

You can try this

var image = new Image();
image.src = $(this).attr("src");
oldW = image.naturalWidth;
oldH = image.naturalHeight;

This approach doesn't work in IE 8 and below versions, because it doesn't support 'naturalWidth' and 'naturalHeight' properties. To achieve the same use this code

var image = new Image();
image.src = $(this).attr("src");
image.onload = function() {
oldW = this.width;
oldH = this.height;
};

Reference : Get Each Image Natural Height With jQuery

Upvotes: 3

KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2178

I have worked on it and this is what I came out with and it works perfectly for me:

$(document).ready(function(){
    get = document.getElementsByClassName('imgs');
    for(var i=0; i < get.length; i++){
        oldH = get[i].naturalHeight;
        oldW = get[i].naturalWidth;
        divH = "500";
        if(oldH > divH){
            newH = divH;
            calW = newH / oldH;
            newW = calW * oldW; 
        get[i].height = newH;
        get[i].width = newW;
        console.log(newH, newW);
        } else {
            newH = oldH;
            newW = oldW;
        get[i].height = newH;
        get[i].width = newW;
        console.log(newH, newW);
        }   
    }
});

Upvotes: 0

Thomas Galue
Thomas Galue

Reputation: 169

<div style="height: 100px">
<img src="random-img.jpg"
style="max-height: 100%; max-width: 100%">
</div>​

This isn't JQuery, but is the easier solution i can give you.

Try and tell me.

Upvotes: 0

Related Questions