Image resize of items jQuery

I have managed to fit automatically the images of the gallery per row depending if it´s horizontal (one image per row) or vertical (two images per row).

The problem now is that I want the images to be scalable (resize on window resize) but I have no idea how to achieve it. How it should me made?

this is my code:

var gallery = new Gallery($('#gallery_images_inner'));

function Gallery(selector){

this.add_module = function(type, image){
    var container = $('<div />' , {
        'class' : 'gallery_container'
    if(type == 'horizontal'){
        var h_ar = image.attr('height') / image.attr('width');
            'width' : selector.width(),
            'height' : selector.width()*h_ar
    if(type == 'vertical'){
            'width' : v_width,
            'height' : v_height
var _this = this;
var gutter = 0;
// start vars for counting on vertical images
var v_counter = 0;
var w_pxls = 0;
var h_pxls = 0;
// iterates through images looking for verticals
    if($(this).attr('width') < $(this).attr('height')){
        h_pxls += $(this).attr('height');
        w_pxls += $(this).attr('width');
// calculates average ar for vertical images (anything outside from aspect ratio will be croped)
var h_avrg = Math.floor(h_pxls/v_counter);
var w_avrg = Math.floor(w_pxls/v_counter);
var v_ar = h_avrg/w_avrg;
var v_width = (selector.width())/2;
var v_height = v_width*v_ar;
    if(parseInt($(this).attr('width')) > parseInt($(this).attr('height'))){
        _this.add_module('horizontal', $(this));
        _this.add_module('vertical', $(this));
    masonry: {
        columnWidth: selector.width() / 2




use percentages for the container containing the image (for both it's width and height).. then also use percentage for the image's width and height as well (it doesn't have to be 100%, it just has to be a percentage relative to its container)


This would be better to solve with CSS. Just set the img width to 100% and it will expand contract with the size of its parent. In the example below .container takes up 25% of the window and the img takes up 100% of that. You can use firebug to change the width of the container and see the difference.

<DOCTYPE html>
        .container {
            width: 25%;
        .container img {
            width: 100%;

    <div class="container">
        <img src="">



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.