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
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
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); andwindow.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>
See this fiddle. I think you'll get the answer. Here is the
[1]: http://jsfiddle.net/mk4q332q/
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