Keep pressing the buttons to see how the image width changes.

Help illustration

Return to tutorial on Image Width

Complete source

<!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>