Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

1 total

Resize image to fit container

Resizes an image to fit into its container, depending on whether the width or height is longer, yet keeping the aspect ratio. Copied from a comment on sitepoint.com.

ffunction resizeImgOO(el) 
{ 
	function imgRatio()
	{ 
		return (el.height / el.width); 
	} 
	function holderRatio()
	{ 
		return (el.offsetParent.offsetHeight / el.offsetParent.offsetWidth); 
	} 
	function fitToContainer()
	{ 
		if(imgRatio>holderRatio) 
		{ 
			el.height = el.offsetParent.offsetHeight; 
		} 
		else 
		{ 
			el.width = el.offsetParent.offsetWidth;	
		} 
	}
	
	this.imgRatio = imgRatio; 
	this.holderRatio = holderRatio; 
	this.resize = fitToContainer; 
}
var img = new resizeImgOO(document.getElementById('yourImgId'));
img.resize();
1 total