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;
For an image with id="i1":
const width = document.getElementById('i1').width;
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.
Demo changing height and width
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.