Created
March 9, 2012 01:35
-
-
Save dimitrikennedy/2004536 to your computer and use it in GitHub Desktop.
JavaScript: aspect ratio maintaining bg image resize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bgSize: function(){ | |
var $background = $('#background'), | |
$bgimage = $background.find('.bgimage'), | |
$loading = $background.find('.loading'); | |
var loadPage = function() { | |
$loading.show();//show loading status image | |
$.when(showBGImage()).done(function(){ | |
//hide the loading status image | |
$loading.hide(); | |
}); | |
}, | |
showBGImage = function() { | |
//adjusts the dimensions of the image to fit the screen | |
adjustImageSize($bgimage); | |
$bgimage.fadeIn(1000); | |
}, | |
initWindowEvent = function() { | |
//on window resize set the width for the menu | |
$(window).bind('resize', function(e) { | |
adjustImageSize($bgimage); | |
}); | |
}, | |
//makes image "fullscreen" and centered | |
adjustImageSize = function($img) { | |
var w_w = $(window).width(), | |
w_h = $(window).height(), | |
r_w = w_h / w_w, | |
i_w = $img.width(), | |
i_h = $img.height(), | |
r_i = i_h / i_w, | |
new_w,new_h, | |
new_left,new_top; | |
if(r_w > r_i){ | |
new_h = w_h; | |
new_w = w_h / r_i; | |
} | |
else{ | |
new_h = w_w * r_i; | |
new_w = w_w; | |
} | |
$img.css({ | |
width : new_w + 'px', | |
height : new_h + 'px', | |
left : (w_w - new_w) / 2 + 'px', | |
top : (w_h - new_h) / 2 + 'px' | |
}); | |
}; | |
loadPage(); | |
initWindowEvent(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment