Find the distance between HTML elements and the browser (or window)

How to find the distance in pixels between an html element and one of the sides of the browser (or window) (left or top) using jQuery?

+41
javascript jquery html position distance
Jan 05 '11 at 7:50
source share
2 answers

You can use the offset function. It gives you the position of the element relative to (left, top) the document:

 var offset = $("#target").offset(); display("span is at " + offset.left + "," + offset.top + " of document"); 

Real-time example In my browser, this example shows that the range we are aiming at is 157.47 (left, top) of the document. This is due to the fact that I applied a great deal of value to the body element and used a span with a separator above it and some text in front of it.

Here is a second example , showing a paragraph in the upper left corner of the document, showing 0.0 as its position (and also showing the spacing later on that are offset both left and top, 129.19 in my browser).

+41
Jan 05 2018-11-11T00:
source share
— -

jQuery.offset needs to be combined with scrollTop and scrollLeft , as shown in this diagram:

viewport scroll and element offset

Demo:

 function getViewportOffset($e) { var $window = $(window), scrollLeft = $window.scrollLeft(), scrollTop = $window.scrollTop(), offset = $e.offset(); return { left: offset.left - scrollLeft, top: offset.top - scrollTop }; } $(window).on("load scroll resize", function() { var viewportOffset = getViewportOffset($("#element")); $("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top); }); 
 body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; } #element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; } #log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- scroll right and bottom to locate the blue square --> <div id="element"></div> <div id="log"></div> 
+28
Jan 05 '11 at 8:17
source share



All Articles