1

Is there any way to get the current position of an element relative to the window, not document

offset get the current position of an element relative to the document

Mohammad Fared
  • 588
  • 1
  • 7
  • 19
  • you could use Element.getBoundingClientRect() https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect – flynorc Dec 26 '16 at 11:38
  • http://stackoverflow.com/a/13930064/5695475 Explains how you can do this using `offset()` `scrollTop()` and `scrollLeft()` – dading84 Dec 26 '16 at 11:40
  • @dading84 Thanks a lot it's worked – Mohammad Fared Dec 26 '16 at 13:14
  • Possible duplicate of [Absolute position of an element on the screen using jQuery](http://stackoverflow.com/questions/13929972/absolute-position-of-an-element-on-the-screen-using-jquery) – dading84 Dec 27 '16 at 10:41

3 Answers3

1

To calculate where the element is positioned relative to the top edge of the viewport, you can use a combination of:

  • getClientBoundingRect() (to determine the position of the element within the document); and
  • window.scrollY (to determine the vertical scroll position of the window).

Then, simply subtract the second value from the first:

var button = document.getElementsByTagName('button')[0];

var div = document.getElementsByTagName('div')[0];
var divRect = div.getBoundingClientRect();

function alertCurrentPosition() {
    var windowVerticalScroll = window.scrollY;
    window.alert('The top of the red square is ' + (divRect.top - windowVerticalScroll) + ' pixels below the top of the viewport');
}

button.addEventListener('click', alertCurrentPosition, false);
body {
height: 1200px;
}

button {
position: fixed;
top: 6px;
left: 6px;
}

div {
position: absolute;
top: 300px;
left: 50%;
width: 100px;
height: 100px;
background-color: rgb(255,0,0);
}
<button>Scroll the Viewport and Click Me</button>
<div></div>
Rounin
  • 27,134
  • 9
  • 83
  • 108
0

See this fiddle. I think you'll get the answer. Here is the

  [1]: http://jsfiddle.net/mk4q332q/
danish farhaj
  • 1,316
  • 10
  • 20
0

This code worked with me well

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

I got the answer from here stackoverflow.com/a/13930064/5695475

Community
  • 1
  • 1
Mohammad Fared
  • 588
  • 1
  • 7
  • 19