I have an img tag, I want to re-size it regarding the browser window, without distortion.
the img takes a (width: 100%), so its height will be greater than browser window. and when the image height be <= browser window, it will stop resizing, else it will re-size.
so; it didn't works !!
here's my code:
<html>
<head>
<title>testawy</title>
</head>
<style type="text/css">
body
{
padding: 0;
margin: 0;
overflow: hidden;
}
</style>
<body>
<img id="str" src="stretch.jpg">
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
$("#str").width($(window).width());
});
$(window).resize(function(){
var x = $(window).height();
var y = $("#str").height();
if (y <= x)
{
$("#str").height('500px');
}
else
{
$("#str").width($(window).width());
}
});
</script>
</body>
</html>
Some time ago, I needed this for a project and I found a lot of resources about the subject here at SO (almost sure this is a duplicated question), but here we go:
<img src="images/bg.jpg" id="bg" alt="">
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
Fiddle: http://jsfiddle.net/7Qcfy/3/
Edit: You was right, my code had few issues, this is the definitive answer... just what you are looking for :D