Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  186] [ 4]  / answers: 1 / hits: 22908  / 13 Years ago, wed, november 16, 2011, 12:00:00

I have an image that I would like to scale to full screen. How would I do this using JavaScript/jQuery? No animation is necessary, just resizing the image.



<img src=something.jpg onload=scaleToFullScreen() />

More From » image

 Answers
19

The only reliable solution is to use a formula to determine maximum scale ratio:



var $img = $('#content img'),
imageWidth = $img[0].width, //need the raw width due to a jquery bug that affects chrome
imageHeight = $img[0].height, //need the raw height due to a jquery bug that affects chrome
maxWidth = $(window).width(),
maxHeight = $(window).height(),
widthRatio = maxWidth / imageWidth,
heightRatio = maxHeight / imageHeight;

var ratio = widthRatio; //default to the width ratio until proven wrong

if (widthRatio * imageHeight > maxHeight) {
ratio = heightRatio;
}

//now resize the image relative to the ratio
$img.attr('width', imageWidth * ratio)
.attr('height', imageHeight * ratio);

//and center the image vertically and horizontally
$img.css({
margin: 'auto',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0
});

[#89077] Tuesday, November 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;