My image is embedded in a table cell. I need to know how far it is from edge of window.
offsetLeft does not work for this. Neither does style.left.

Dani AI

Generated

Brief checklist and a simple native approach to cover the common pitfalls mentioned by and the jQuery example from .

offsetLeft and style.left are relative to an element’s offsetParent or the element’s positioned box, not necessarily the browser viewport. If you need the distance from the window (the viewport) use getBoundingClientRect(); if you need document/page coordinates add the current scroll. Also remember: measurements can be zero or wrong if the image hasn’t finished loading, the element is display:none, or CSS transforms are applied.

Example (native, cross‑browser):

// viewport coordinates (distance from window edges)
const rect = img.getBoundingClientRect();
const fromLeftOfWindow = rect.left;
const fromTopOfWindow  = rect.top;

// page/document coordinates (distance from document origin)
const scrollX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
const scrollY = window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop  || 0;
const pageX = rect.left + scrollX;
const pageY = rect.top  + scrollY;

Troubleshooting notes:

  • Wait for the image to load (use img.onload or window.onload) before measuring.
  • Positioning: position:fixed yields viewport distances directly; absolute/relative inside table cells will be relative to ancestors.
  • CSS transforms, zoom, and fractional pixels affect results; use Math.round if you need integers.
  • If results still look wrong, temporarily add an outline/background to the element to verify the visual box you're measuring.

This covers both the “distance from the window” (viewport) case and the “distance from the document” case while avoiding offsetParent surprises.

Recommended Answers

All 2 Replies

Here is a simple example... seems to work. show your relevant code..maybe you have some other issue.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var i = $( "#img1" );
var offset = i.offset();
$("#pos").text( "left: " + offset.left + ", top: " + offset.top );

});
</script>
</head>
<body>     
<span id="pos"></span>
<img id="img1" src="" width="250" height="250" style="position:fixed;top:50px;left:50px"/>
</body>
</html>

Thank you. Your code is very helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.