Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase / decrease image size preserving aspect ratio on click

Tags:

jquery

I want to be able to increase (zoom in) and decrease (zoom out) an image and maintain the aspect ratio.

I have created a simple example but don't know how to maintain the aspect ratio.

Is it also possible to set a minimum size when decreasing?

Thanks

HTML

<div id="image-container">
     <img src="Image.jpg" alt=""/>
</div>
<div id="image-controls">
     <input id="zoom-in" value="+" type="submit" />
     <input id="zoom-out" value="-" type="submit" />
</div>

JQuery

$(document).ready(function() {

var img = $('#image-container img');
var zoomWidthIncrement = img.width() * 1/3;
var zoomHeightIncrement = img.height() * 1/3;

$("#zoom-in").click(function (e){
    img.css({width: img.width() + zoomWidthIncrement, height: img.height() + zoomHeightIncrement});
e.preventDefault();
});

$("#zoom-out").click(function (e){
    img.css({width: img.width(function(i, w) { return w - zoomWidthIncrement; }), height: img.height(function(i, w) { return w - zoomWidthIncrement; })
});
e.preventDefault();
});
});
like image 633
luke2012 Avatar asked Feb 23 '26 02:02

luke2012


1 Answers

Just change the width or height, not both. The browser will scale the image proportionally automatically.

jsFiddle example.

like image 181
j08691 Avatar answered Feb 24 '26 16:02

j08691