Resize images to Fit Browser Window

Posted by Anandajoti on Monday, 7th January, 2013

Yesterday I mentioned that I had just introduced the WOW-slider to my Photo Dharma website. From a developer’s point of view there is one big drawback with it, which is that you must fix the size of the photo first (e.g. 800px x 600px). The problem with that is we don’t know the size of the browser window people will be using, so it may be too small, or too big.

To get round that problem I wrote a new and fairly simple function, which first looks at the viewport, and then resizes the photograph to find the best fit for the screen. This is the javascript code for it, which I have annotated in the hope that it may help someone else.

Note that the script will only work if all the photos are the same aspect ratio. The ratio presumed here is 4×3 (1.33:1). The code can be adjusted for other ratios easy enough.