I continue to develop my expertise in designing web sites for mobile devices. I’ve been dissatisfied with the display of my travel notes on my iPod Touch. Wide images would force the page width to exceed the limited width of the screen which is only 320 pixels. This made the page hard to read unless I zoom in and scroll around. However, I did not want to resize all my images because I also use my travel notes on the desktop as a regular help file. Ideally I want a style sheet for mobile devices that reformats the page to look decent without changing any of the content.
The solution I found was to use jQuery (i.e. JavaScript) to scale the images to 320 pixels. My code checks the width of every image on the page, and if the width is greater than 320 pixels, it surrounds the image with a div that has a CSS class to scale the image. However images with a specified height tended to look distorted so I added some code to remove the height attribute from the img tag.
1: $(document).ready(function() {
2: $("img").each(function(i) {
3: var width = $(this).width();
4: if (width > 320) {
5: $(this).wrap('<div class="scaleimg"></div>');
6: $(this).removeAttr("height");
7: }
8: });
9: });
A couple of things to note here. First, jQuery does work on the iPhone and iPod Touch. It does not appear to effect performance. Second, I could have set the width to 320 pixels instead of wrapping the image in a div. I was experimenting with some CSS to set the image width using em relative sizes so I took that approach. I surrounded the script tags with conditional comments to prevent Internet Explorer from using the JavaScript. Help files use Internet Explorer to display help topics which are actually web pages, so I don’t need to worry about other browsers.
4 Responses to Mobile Web Site Design – Scale Images