
Keep pressing the buttons to see how height and width change.
Return to tutorial on Image Height | Image Width
const image = document.getElementById('i1');
const message = document.getElementById('msg');
function showSize() {
message.textContent = `Height: ${image.height}, Width: ${image.width}`;
}
function resizeImage(action) {
let height = image.height;
let width = image.width;
switch (action) {
case 'up':
if (height < 300) height *= 2;
break;
case 'down':
if (height > 10) height = Math.max(10, Math.round(height / 2));
break;
case 'width-up':
if (width < 400) width *= 2;
break;
case 'width-down':
if (width > 10) width = Math.max(10, Math.round(width / 2));
break;
}
image.width = width;
image.height = height;
showSize();
}
document.querySelectorAll('[data-resize]').forEach((button) => {
button.addEventListener('click', () => resizeImage(button.dataset.resize));
});
image.addEventListener('load', showSize);
if (image.complete) showSize();<img src="images/help.jpg" id="i1" alt="Help illustration">
<button type="button" data-resize="up">Expand ( Height )</button>
<button type="button" data-resize="down">Compress ( Height )</button>
<button type="button" data-resize="width-up">Expand ( Width )</button>
<button type="button" data-resize="width-down">Compress ( Width )</button>
<div id="msg" aria-live="polite"></div><!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Change image height and width</title></head>
<body>
<img src="images/help.jpg" id="i1" alt="Help illustration">
<button type="button" data-resize="up">Expand ( Height )</button>
<button type="button" data-resize="down">Compress ( Height )</button>
<button type="button" data-resize="width-up">Expand ( Width )</button>
<button type="button" data-resize="width-down">Compress ( Width )</button>
<div id="msg" aria-live="polite"></div>
<script>
const image = document.getElementById('i1');
const message = document.getElementById('msg');
function showSize() {
message.textContent = `Height: ${image.height}, Width: ${image.width}`;
}
function resizeImage(action) {
let height = image.height;
let width = image.width;
switch (action) {
case 'up':
if (height < 300) height *= 2;
break;
case 'down':
if (height > 10) height = Math.max(10, Math.round(height / 2));
break;
case 'width-up':
if (width < 400) width *= 2;
break;
case 'width-down':
if (width > 10) width = Math.max(10, Math.round(width / 2));
break;
}
image.width = width;
image.height = height;
showSize();
}
document.querySelectorAll('[data-resize]').forEach((button) => {
button.addEventListener('click', () => resizeImage(button.dataset.resize));
});
image.addEventListener('load', showSize);
if (image.complete) showSize();
</script>
</body>
</html>