Axesh Ajmera
Axesh Ajmera

Reputation: 383

How to manipulate width of multiple images in javascript

I have multiple images and i wnat to place all of them in a single line.How should i manipulate the width of images such that the sum of width of al images does not exceed the browser's width.??

Upvotes: 3

Views: 233

Answers (3)

unomi
unomi

Reputation: 2672

If you have variable width images you could go with something like this:


/**
*@param contId {string} id of the container element
*/
var imgResize = function(contId) {
    var imgs = [], totalWidth = 0, ratio = 0, containerWidth = 0;
    var cont = document.getElementById(contId);
    var child = cont.firstChild;
    while(child.nextSibling){
        if(child.tagName && child.tagName.toUpperCase() === 'IMG'){ 
            var imgW = child.clientWidth;
            imgs.push({node: child, width: imgW});
            totalWidth += imgW;
        }
        child = child.nextSibling;
    }
    ratio =  cont.clientWidth / totalWidth;

    imgs.forEach(function(img){
        var cWidth = Math.floor(ratio*img.width);
        img.node.style.cssText='width:'+cWidth+'px';
    });
};

/**
* Fire it on window resizes, ooohh shiny
*/
window.onresize=function(){imgResize('container');};

Keep in mind that you should probably do something like



img{border:0px;display:block;float:right;}
.imgContainer{font-size:0px;padding:0px;width:100%;/*for example*/}

Getting this to work in less than modern browsers is left as an exercise to the reader. And yes, using a framework is a fine idea, I would recommend YUI, so good that even Russians have been known to use it.

Upvotes: 2

Anthony
Anthony

Reputation: 12397

var width = (window.width / numImages) - margin;

Upvotes: 0

Mechlar
Mechlar

Reputation: 4974

To be able to target them all at the same time give them all the same class or go from a containing id and get them by node name. After targeting them get their widths.

To get the widths into variables with jquery:

var $allImages = $('img.myImages');//all images need the same class

var allImagesW = $allImages.width() * $allImages.length;//you might want to use .outerWidth() to account for borders and padding, and .outerWidth(true) to include margins.

var windowW = $(window).width();

Upvotes: 0

Related Questions