The JavaScript HTMLImageElement object represents an HTML <img> element. Once you select an image, you can read its displayed size, intrinsic size, alternative text, position, source and other properties, or update supported properties when an interaction requires it.
const image = document.getElementById('my_image');
<img src="../images/top2.jpg" alt="plus2net.com tutorial site" id="my_image" width="150" height="30">
The values below are generated from that image object. Resize the browser window and the window dimensions update automatically. The original tutorial also linked to the HTML <body> tag reference; that link is retained here.
const image = document.getElementById('my_image');
const output = document.getElementById('imageDetails');
function showImageDetails() {
const rows = [
`Height: ${image.height}`,
`Width: ${image.width}`,
`naturalHeight: ${image.naturalHeight}`,
`naturalWidth: ${image.naturalWidth}`,
`Alt text: ${image.alt}`,
`offsetTop: ${image.offsetTop}`,
`offsetLeft: ${image.offsetLeft}`,
`window.innerWidth: ${window.innerWidth}`,
`window.innerHeight: ${window.innerHeight}`,
];
output.textContent = rows.join('\n');
}
image.addEventListener('load', showImageDetails);
window.addEventListener('resize', showImageDetails);
if (image.complete) showImageDetails();
| Property | Purpose |
|---|---|
alt | Alternative text for the image. |
height | The rendered height in CSS pixels. |
width | The rendered width in CSS pixels. |
naturalWidth | The intrinsic, density-corrected width of the loaded image. |
naturalHeight | The intrinsic, density-corrected height of the loaded image. |
| Position | Changing image position with CSS. |
| Offsets | Reading the image position relative to its offset container. |
| Align | Historical image alignment property; CSS layout is preferred. |
| Border | Historical image border property; CSS borders are preferred. |
width and height describe the size at which the image is currently drawn. naturalWidth and naturalHeight describe the image's intrinsic dimensions after it has loaded.
console.log(image.width, image.height);
console.log(image.naturalWidth, image.naturalHeight);
The original tutorial also demonstrated the HTML image align and border properties. Those remain linked above for historical/search value, but new pages should normally use CSS such as float, flex/grid layout and border.
Image SlideShow Script using navigational buttons
Image Loading to cache while page load by Image object
Reloading the image without refreshing the page
Image Rotator Script for automatic Slideshow
Image Move across by button click
Image Move continuously across screenAuthor & 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.