Reputation: 97
I've set up a small demo that automatically resizes an image to fit inside it's container div when it is clicked.
It works by taking the size of the image then dividing that by the size of the box and working out which ratio is higher before resizing the image based on either width or height accordingly. It's probably better to look at the code to see how it works.
The only problem is that it's rather glitchy. It does work but instead of resizing based on the image's width it seems to be calculating it based on the browser width but still passing on the correct values on the resize.
Have a look at it at the two links below and have a play at resizing the browser window to see the glitch. I have crossed out the overflow:hidden;
attribute so you can see the dimensions of the image outside the div.
Take a look at the code here: http://jsfiddle.net/sambeckhamdesign/NVAGG/11/
View the fullscreen result here: http://jsfiddle.net/sambeckhamdesign/NVAGG/11/embedded/result/
or read the jQuery here
$('img').click(function() {
function wr(){
var imageWidth =
$(this).width()/250;
return imageWidth;
}
function hr(){
var imageHeight =
$(this).height()/200;
return imageHeight;
}
function nh(){
var newHeight =
$(this).height()/hr();
return newHeight;
}
function nw(){
var newWidth =
$(this).width()/wr();
return newWidth;
}
if (wr() > hr()){
$(this).css('width', nw() + 'px');
}else{
$(this).css('height', nh() + 'px');
}
});
Upvotes: 0
Views: 599
Reputation: 4632
Right off the top of my head, I'd bet this is a closure issue. Since you're referencing 'this' inside the functions, which are also inside of another function, 'this' isn't attached to the image but rather to the window. You could update the functions to pass a reference to 'this' as an argument, or set up a variable scoped to the click function that references back to 'this'.
Upvotes: 1