Bri Manning

Yes, I Position My Background Image with jQuery

October 25, 2009

So, notice that green hook on the left there? How much of it can you see? And what happens if you resize the window?

Now, if you’re a front-end guy, you know that a background image cannot extend outside of an element. But what if you want to position that background relative to the position of an element, but outside of that element? I had the same problem…

Now, I’m a huge fan of jQuery, so I decided to go that route. Here’s what I did:

$('body')
    .css('background-position',
        $('#container').offset().left - 320 + 'px ' +
        $('#container').offset().top + 'px');

What does that do? jQuery finds the body element: $('body') and it sets the background position using .css('background-position', value). But, we need to get the position of my #container element, so we do that using $('#container').offset().left (with a 320px nudge) and $('#container').offset().top.

Put that in jQuery’s $(document).ready(function() and huzzah!

Well, what happens if you resize? Uh-oh, one more thing to do. I promise it won’t be hard though. Let’s just bring jQuery to the rescue again using $(window).bind('resize', function(). And, to keep up with DRY coding principles, we’ll pull it out into an alignBG() function, giving us:

function alignBG(){
    $('body')
        .css('background-position',
            $('#container').offset().left - 320 + 'px ' +
            $('#container').offset().top + 'px');
}
 
$(document).ready(function(){
    alignBG();
	
    $(window).bind('resize', function() {
        alignBG();
    });
}

And there you have it! That’s how you can position a background image based on a different element’s location in jQuery making sure that it’s in the right place on a resize.