JavaScript Image Height

The height property of an image element lets JavaScript read or change the height at which the image is rendered.

const height = document.getElementById('i1').height;
document.getElementById('i1').height = 100;
Table of Contents

Reading image height Top ↑

const height = document.getElementById('i1').height;

Assigning height to an image Top ↑

document.getElementById('i1').height = 100;

Changing only one dimension may change the rendered aspect ratio depending on how the other dimension is constrained. For layout, responsive CSS is often preferable.

Working demos Top ↑

Demo managing height of image

Demo changing height and width

Complete source Top ↑

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Change image height with JavaScript</title></head>
<body>
<button type="button" id="expand">Expand</button>
<button type="button" id="compress">Compress</button>
<img src="images/help.jpg" id="i1" alt="Help illustration">
<script>
const image = document.getElementById('i1');
const expand = document.getElementById('expand');
const compress = document.getElementById('compress');

function resizeHeight(direction) {
  let height = image.height;
  if (direction === 'up' && height < 300) height *= 2;
  if (direction === 'down' && height > 5) height = Math.max(5, Math.round(height / 2));
  image.height = height;
}

expand.addEventListener('click', () => resizeHeight('up'));
compress.addEventListener('click', () => resizeHeight('down'));
</script>
</body>
</html>

Managing Width of Image Image Object




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer