A background which adapts

to the size of the window

  • The image automatically moves to the center when the window resizes.
  • The width / height ratio of the image is preserved: no deformation.
  • If this ratio is lower than that of the window,
    then the image gets the window's width and repositions itself vertically at the center.
  • If this ratio is greater than that of the window,
    then the image gets the window's height and repositions itself horizontally at the center.

<script type="text/javascript">
jQuery.noConflict();
(function($) { 
  $(function() {
	// code using $ as alias to jQuery

	function redim() { // For MSIE which do not know background-size:cover
		var $image = $("#fond").find("img")
			, format_im = $image.width() / $image.height()
			, largeur_fen = $(window).width()
			, hauteur_fen = $(window).height()
			, format_fen = $(window).width() / $(window).height();
		if (format_im < format_fen) {
			var nouvelle_hauteur = Math.ceil( largeur_fen / format_im ); // Cross product
			$image.css({"width": largeur_fen + "px", "height": nouvelle_hauteur + "px", "left": "0px", "top": "-"+ Math.abs( (nouvelle_hauteur - hauteur_fen)/2 ) + "px" });
		} else {
			var nouvelle_largeur = Math.ceil( hauteur_fen * format_im ); // Cross product
			$image.css({"height": hauteur_fen + "px", "width": nouvelle_largeur + "px", "top": "0px", "left": "-"+ Math.abs( (nouvelle_largeur - largeur_fen)/2 ) + "px" }); 
		}
	} // End of redim()

	$(document).ready(function(){
		var $fond = $("#fond");
		if (navigator.appVersion.indexOf("MSIE") > -1) { // If the browser is MSIE
			$fond.append("<img src=/imgdo/Goldorak.jpg alt=Goldorak width=1920 height=1920 style=position:absolute;border:0; />")
				.css("opacity","0.8")
				.delay(200).stop(false,true) // DO NOT empty the queue but terminates the current animation immediately
				.fadeIn(1200);
			redim(); // When loading the page
			$(window).on("resize", function(e){ // When resizing the window
				//if (e.type == "resize") {
					redim();
				//}
			});
		} else { // For the others, we use background-size
			$fond.css({"background":"url(/imgdo/Goldorak.jpg) no-repeat center fixed"
							,"-webkit-background-size":"cover"
							,"-moz-background-size":"cover"
							,"-o-background-size":"cover"
							,"background-size":"cover"
				})
				.css("opacity","0.8")
				.delay(400)
				.fadeIn(1200);
		}
	}); // End of ready

  });
})(jQuery);
</script>

 

Last update : Sunday, march, 24th 2013 Design by Minh-Dung DO