jQuery image scaler
I've been tinkering around with jQuery a bit lately (see the show/hide sidebar trick above). I know virtually nothing about javascript, but jQuery allows a guy like me to do some pretty cool tricks and it has a relatively short learning curve as it is very intuitive and uses standard CSS selectors to do its work.
One of the problems I've run into through several theme changes on my blog is the size of images in my posts. The last time I changed themes I shrank the width of the content area from around 510px to more like 460px. Most of the images I had placed in posts were somewhere around 500px wide, which made them overflow into the sidebar area. I looked into a few different ways to fix this, and one approach was to use CSS to solve the problem.
.post img {
max-width:440px;
width: expression(this.width > 440 ? 440: true);
}
Internet Explorer doesn't support the max-width attribute, so the width: expression mumbo jumbo is supposed to trick it into shrinking the image. It seemed to work fine, until I visited my blog from my aunt and uncle's Mac a few months ago. The browser shrunk the width but not the height, leaving a strange looking, vertically stretched version of an image in this post. Not good.
I looked around to see if there was some jQuery code out there that automatically shrank an image if it was wider than a certain width. I didn't find anything out there, so I wrote my own code.
The following image is 1000 x 750 pixels, but jQuery shrinks it down to 440px wide so it fits perfectly as it should.
The code is pretty simple. You have to configure the max width for the images and also the CSS selector code so it knows which images to scale. After that jQuery examines each image to see if it is wider than the max width. If it is, it proportionally resizes the image down to the max width. I thought it would also be nice to allow the visitor to view the full-sized image, so jQuery turns the scaled down image into a link to the original.
Of course, in a perfect world one would size all of his images to fit the new layout and conserve bandwidth. Also, if a visitor has javascript disabled they will see the full-sized image, which may or may not bother you. Still, this seems like a pretty simple solution to keep large images from breaking your page layout.
You can view the sample code here. It tested fine in IE6, IE7, and Firefox 2.0, all on Windows. In Opera it worked sometimes, but not others (?). Let me know if you find a bug and/or if you have any browser optimization tips.




