Resize images inside element with Mootool
Written by Saran on
October 11, 2012,
Updated
December 21, 2013In my another website, some images were larger than DIV element, and it was causing whole layout to distort. It would've been little easier with jQuery but since I was using Mootool library, I needed to come up with some sort of resize snippet, so I wrote this small mootool function which will calculate width of DIV element and resize images inside it to fit to its size.
Resize Function
Let's say your element size is 100px width, but you don't know how big your images will be, may be 300px or 500px, just use this Mootool Image resize function, it will automatically resize all images to fit within the element width. [cc lang="js"] function resizeImage(ImageContent, myElement) //resizeImage(Images,Element) { var ElementSize = myElement.getSize(); //size of elementArray.each(ImageContent, function(thisImage, index) { getElementWidth = ElementSize.x; // width of element getImageWidth = ImageContent[index].getSize().x; //width of image getImageHeight = ImageContent[index].getSize().y; //Height of imagevar ratio = getImageHeight / getImageWidth; //get image ratioif(getImageWidth>getElementWidth && ratio <= 1){//image image is larger than element width ImageContent[index].setStyle('width',getElementWidth+'px'); //set image width ImageContent[index].setStyle('height',(getElementWidth*ratio)+'px'); //set image height } }); } [/cc]
Usage
Usage is pretty easy, just specify image elements and element id containing images. [cc lang="js"] [/cc]
Complete Code
Here is complete code, but unfortunately I do not have any demo for this function. You just have to copy/save it as HTML file and try it on your browser. I hope it helps, if there's better way to do it let me know, good luck! [cc lang="html"]
Image Resize [/cc]