JavaScript Image Width

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

const width = document.getElementById('i1').width;
document.getElementById('i1').width = 200;
Table of Contents

Reading image width Top ↑

For an image with id="i1":

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

Assigning width to an image Top ↑

document.getElementById('i1').width = 200;

This changes the rendered width. If you want responsive layout rather than an interaction-driven resize, CSS such as max-width:100% is usually a better fit.

Working demos Top ↑

Demo managing width of image

Demo changing height and width

Complete source Top ↑

The original page gave visitors a full page they could copy. That facility is preserved with modern event listeners:

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Change image width 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 resizeWidth(direction) {
  let width = image.width;
  if (direction === 'up' && width < 300) width *= 2;
  if (direction === 'down' && width > 5) width = Math.max(5, Math.round(width / 2));
  image.width = width;
}

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

Managing Position 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