Archive for the ‘Javascript’ Category

Emulate max-width / max-height for Internet Explorer (no extra work needed!)

Saturday, July 11th, 2009

As I’m sure many of you know, Internet Explorer (even IE8) completely ignores the max-width and max-height css properties. I did some Googling but unfortunately all of the stuff I found was for manually setting the max-width/max-height or some similar buffoonery. I’ve written a nice Javascript (uses jQuery) function that you can include in your head tag to emulate proper detection of the max-width and max-height css attributes without doing any extra work after that (so long as it’s in the head of the content you’re loading with max-width/max-height attributes). Feel free to use it but please keep my copyright statement if you don’t mind!

Cheers and happy designing:

function css_emulateMaxWidthHeight() {
/* (c) Evan Roberts - 7/10/2009
www.GoWFB.com - Wholesale Furniture Brokers
Everyone is free to use/mdoify this but please keep the copyright statement!
*/

	$('img').each(function() {		

		if( $(this).css('max-width') != 'none' || $(this).css('max-height') != 'none' ) {

			max_width = $(this).css('max-width').replace(/[^0-9]/g, '');
			max_height = $(this).css('max-height').replace(/[^0-9]/g, '');		

			if( $(this).width() > max_width || $(this).height() > max_height ) {
				if( (max_width / $(this).width()) < (max_height / $(this).height()) ) {
					$(this).css('height', Math.round($(this).height() * (max_width / $(this).width())));
					$(this).css('width', max_width);
				} else {
					$(this).css('width', Math.round($(this).width() * (max_height / $(this).height())));
					$(this).css('height', max_height);
				}

			}
		}
	});
}

$(document).ready(function() {

	css_emulateMaxWidthHeight();

});