jQuery Plug-in: Scalable Background Image

A few days ago a friend approached me about an interesting background effect he has seen on a website and how he wanted to implement it into his website. I was curious about how it worked so decided to build a jQuery plug-in that does it for you; hooray for jQuery (again).

The effect is a scalable background image; as you expand / contract the browser window the background image scales up and down with respectively. Unfortunately it isn’t possible to do using only CSS 2.1; it’s possible using CSS3 using the background-size property, though not yet widely supported. The technique doesn’t use a background image, it uses an absolutely positioned image to achieve the same effect; so it could be considered a hack. If you’re not sure what I mean, here’s a demo. It’s quite simple to use; here’s the basic HTML:

1
2
3
4
5
6
<div id="container">
    <!-- Content here -->

    <!-- This Image will resize with every window resize -->
    <img id="imageID" src="images/our-image.jpg" alt="Fake background image" >
</div>

The plug-in is called using (with custom settings):

1
2
3
4
5
6
7
8
//Plug-in usage
jQuery(function($){
    $("#container").backgroundScale({
        imageSelector: "#imageID",
        centerAlign: true,
        containerPadding: 100
    });
});

The plug-in accepts an object as an argument with custom user settings:

  • imageSelector: The ID or class of the fake background image (default: “#bgImage”).
  • centerAlign: Align the image in the center of the container, both vertically and horizontally (default: true).
  • containerPadding: Padding in pixels that expands the image slightly in relation to it’s container to minimise seeing behind the image when scaling up and down in certain browsers (default: 80).

A couple of things to note:

  1. You must have a container div for the image, using the body tag returns strange results.
  2. The resize event in Firefox is a little weird, it doesn’t fire continuously as you scale up and down so you can sometimes see the container background when scaling. There are plug-ins that make the resize event consistent across browsers.
  3. Since this is a JavaScript dependent effect it may be worth adding the fake background image using JavaScript
  4. It’s better to use a larger image for scaling, as expanding a smaller image will look fuzzy and out of focus.

Any questions / ideas for expanding this plug-in then leave a comment. View a demo (version 0.1 – updated 17th Feb 2010).