Monthly Archives: June 2009

Resize images using jQuery

flattr this!

UPDATE: I have created a plugin that dynamically resizes the images using jQuery. It basically does the same job but is really easy to use and is optimized better (minified).

Recently I needed a script to resize images on the page. I did not want to lose the actual resolution but just wanted to create thumbnails on the go.

I spent some time searching but could not find anything suitable. The options I found were just too much while I needed something simple. At the end, I ended up writing some own code (I’m a coder after all :P).
var max_size = 200;
$("img").each(function(i) {
if ($(this).height() > $(this).width()) {
var h = max_size;
var w = Math.ceil($(this).width() / $(this).height() * max_size);
} else {
var w = max_size;
var h = Math.ceil($(this).height() / $(this).width() * max_size);
}
$(this).css({ height: h, width: w });
});

The script resizes the images without distorting the proportions. First of all, a variable is declared called max_size that is set to the maximum height or width that the picture needs to be resized to. Then using jQuery we match all img elements and using the each function, we go through each one of them resizing them as necessary. The if statement checks which side of the image needs to be kept to the maximum and the other one is calculated proportionally.

In the final line, the new height and width values are assigned using CSS. Neat eh ;)

AddThis, Internet Explorer and JavaScript

flattr this!

While working with Internet Explorer 7, I got this error:

Object doesn't support this property or method
Line: 2
Char: 13907
URI: addthis.com/js/250/addthis_widget.js

The thing that hurt more was, Chrome and Firefox were behaving properly. I spent some time Googling the error but found nothing interesting. I gave up on that front and decided to have a peek in the AddThis JavaScript.

A bit more look around, I found something very interesting. IE7 has some scoping issue and it was picking up ‘my’ variable instead of AddThis counterpart (in my case it was variable called “c” that I had declared in my own JavaScript that was causing the problem).

Change the variable in your own javascript code to anything else and we all can live happily ever after.