Demo of Image offset in JavaScript

Click Show Details to display the image's current offsetLeft and offsetTop values.

Help icon used for offset demo

Return to Image offset tutorial

JavaScript

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);

HTML

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

Complete working page

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