Mashupdesign Blog : Web Design, Coding, and UI/UX

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;
}