offsetLeft and offsetTop return an element's position in pixels relative to its offsetParent. For a positioned image, they are useful when you need the image's current layout position before moving it or displaying coordinates.
const image = document.getElementById('i1');
console.log(image.offsetLeft);
console.log(image.offsetTop);
The values are read-only numbers. They are not necessarily distances from the browser window itself; the reference is normally the nearest positioned ancestor that becomes the image's offsetParent.
First select the image. The original plus2net example uses getElementById(), which remains a simple way to access a uniquely identified image.
const image = document.getElementById('i1');
const x = image.offsetLeft;
const y = image.offsetTop;
<img src="images/help.jpg" id="i1" alt="Help icon">
The original demo's Show Details control is preserved. The modern version places the image inside a responsive positioned area so the demo remains usable on smaller screens.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo of Image offset in JavaScript</title>
</head>
<body>
<div id="offset-area" style="position:relative; min-height:260px; border:1px solid #ccc; overflow:hidden;">
<img src="images/help.jpg" id="i1" alt="Help icon used for offset demo"
style="position:absolute; left:min(50%, 500px); top:80px;">
</div>
<button type="button" id="show-details">Show Details</button>
<div id="msg" aria-live="polite"></div>
<script>
const image = document.getElementById('i1');
const output = document.getElementById('msg');
const button = document.getElementById('show-details');
function showOffset() {
output.textContent = `X: ${image.offsetLeft} Y: ${image.offsetTop}`;
}
button.addEventListener('click', showOffset);
window.addEventListener('resize', showOffset);
</script>
</body>
</html>
offsetLeft and offsetTop are relative to the offsetParent. If you instead need an element's position relative to the current viewport, use getBoundingClientRect().
const rect = image.getBoundingClientRect();
console.log(rect.left, rect.top);
If responsive layout, fonts, surrounding content, or the browser width changes, the image's layout position may change too. The demo recalculates the displayed values after window resize so you can observe that behavior.
offsetTop and offsetLeft again instead of assuming old values are still correct.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.
| krati jain | 24-10-2014 |
| I feel this is a good effort krati jain | |
| vitthal chandane | 09-04-2015 |
| i fill that it is nice solution which i help to solve my problem. | |