I recently started a project were I wanted the background image to scale to the size of the window. I was able to make it work with the following code:
<script>
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(function() {
resizeBg();
}).trigger("resize");
});
</script>
</head>
<body>
<img src="images/ij_background.jpg" id="bg" alt="">
</body>
</html>
The problem is that the background image will load the full size image, and then scale to the window size, which is a little ugly. I want the image to load, scale, and then be displayed with a fade. I became a little stuck since I’m a little new to jQuery. Here is what I have so far.
You can load the image hidden, resize it, and then fade it in. This approach requires that JavaScript be enabled on the client (about 98% of people have it enabled, but a
noscriptfallback for the other 2% might be worthwhile). It would look something like this (live copy):Note that we’re no longer waiting for the overall
window#loadevent to fire, we only care that the DOM is ready and that this specific image is finished loading.