JSFiddle - React, Tailwind, and code Playground
by cgtrman
HTML
<div>
<button class="resizeButton" data-maxHeight="150" data-maxWidth="150">Resize</button><br>
<img id="testImage1" src="http://2.bp.blogspot.com/_F_owTM6w2wM/S9GehTPtioI/AAAAAAAAEQI/jL5Ebji0kbY/s1600/hp-compaq-6830b-notebook-pc.jpg">
</div>
<br><br>
<div>
<button class="resizeButton" data-maxHeight="150" data-maxWidth="150">Resize</button><br>
<img id="testImage2" src="http://photos.smugmug.com/photos/344288161_jkvhV-L.jpg">
</div>
JavaScript
function resizeImage(id, maxHeight, maxWidth) {
// assumes the image is already loaded
// assume no height and width is being forced on it yet
var img = document.getElementById(id);
var height = img.height || 0;
var width = img.width || 0;
if (height > maxHeight || width > maxWidth) {
var aspect = height / width;
var maxAspect = maxHeight / maxWidth;
if (aspect > maxAspect) {
img.style.height = maxHeight + "px";
} else {
img.style.width = maxWidth + "px";
}
}
}
// test bed
$(".resizeButton").click(function() {
resizeImage($(this).nextAll("img").attr("id"),
$(this).attr("data-maxHeight"),
$(this).attr("data-maxWidth"));
});