JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<div class="before"></div>
<div class="sticky" id="sticky">
<div class="result">
<div>pageYOffset: <span class="result-scroll" id="result-scroll"></span></div>
<div>getBoundingClientRect().top: <span class="result-rect-top" id="result-rect-top"></span></div>
<div>offsetTop: <span class="result-offset-top" id="result-offset-top"></span></div>
</div>
</div>
<div class="after"></div>
</div>
<div class="more-content"></div>
CSS
html, body {
margin: 0;
}
.before {
height: 50vh;
background: #111;
}
.after {
height: 50vh;
background: darkblue;
}
.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
height: 50vh;
background: black;
color: #555;
font: 1em sans-serif;
}
.result {
position:absolute;
left:10vw;
bottom: 10vw;
}
.result-scroll,
.result-rect-top,
.result-offset-top{
color: white;
}
.more-content {
height: 100vh;
background: #111;
}
JavaScript
let sticky = document.getElementById('sticky');
let resultScroll = document.getElementById('result-scroll');
let resultRectTop = document.getElementById('result-rect-top');
let resultOffsetTop = document.getElementById('result-offset-top');
function showPosition() {
resultScroll.innerHTML = window.pageYOffset;
resultRectTop.innerHTML = sticky.getBoundingClientRect().top;
resultOffsetTop.innerHTML = sticky.offsetTop;
}
showPosition();
window.addEventListener('scroll', function(){
window.requestAnimationFrame(showPosition);
});