Resize Background image with Jquery

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.dimensions.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		var $winwidth = $(window).width();
		$("img.source-image").attr({
			width: $winwidth
		});
		$(window).bind("resize", function(){
			var $winwidth = $(window).width();
			$("img.source-image").attr({
				width: $winwidth
			});
		 });
	});
</script>

In order to get this inline image to behave more like a background image, we can use that unique class we applied to apply some absolute positioning.

img.source-image {
	position: absolute;
	top: 0;
	left: 0;
}

Because of this absolute positioning, anything that you want to put over it will also need positioning and a higher z-index value. If your source image is particularly tall, or your browser window is particularly wide, the image could easily become taller than your browser window and force a vertical scrollbar. In order to prevent this, simply set the overflow value on your body to hidden:

body {
  overflow: hidden;
}
Or Just css

Forget this javascript business! Thanks to Anders comment pointing out Stu Nicholls version, here is an even better way to handle this without the need for any javascript at all!

Since we already have a unique class on the image, the image is absolutely positioned, and the scrollbars thing is already taken care of, let’s just set the width using a percentage directly in the CSS:

#img.source-image {
	width: 100%;
	position: absolute;
	top: 0;
	left: 0;
}

This entry was posted on Friday, February 27th, 2009 at 8:04 pm and is filed under css, tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “Resize Background image with Jquery”

Entrepreneur Ideas June 25th, 2011 at 7:29 pm

Related……

[...]just beneath, are quite a few totally not associated web sites to ours, however, they are surely worth going over[...]……

calories blog July 15th, 2011 at 10:44 am

Super!…

Because i adore your posts i thought i would show my appreciation by making a comment. Thanks alot for the good times you give :)

My website July 15th, 2011 at 11:01 pm

Loving your blog…

I often thought commenting was stupid, but for this blog i shall give it a go. Im loving it!…

Prestashop Templates November 2nd, 2011 at 11:25 pm

Check This Out…

[...]Here are some of the sites we recommend for our visitors[...]…

resize January 6th, 2012 at 11:15 am

Yahoo results…

While browsing Yahoo I discovered this page in the results and I didn’t think it fit…

Leave a Reply

You must be logged in to post a comment.