JavaScript get window X/Y position for scroll

Maybe more simple;

var top  = window.pageYOffset || document.documentElement.scrollTop,
    left = window.pageXOffset || document.documentElement.scrollLeft;

Credits: so.dom.js#L492


Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

window.addEventListener("scroll", function(event) {
  
    var top = this.scrollY,
        left = this.scrollX;
  
    var horizontalScroll = document.querySelector(".horizontalScroll"),
        verticalScroll = document.querySelector(".verticalScroll");
    
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";
  
}, false);
*{box-sizing: border-box}
:root{height: 200vh;width: 200vw}
.wrapper{
    position: fixed;
    top:20px;
    left:0px;
    width:320px;
    background: black;
    color: green;
    height: 64px;
}
.wrapper div{
    display: inline;
    width: 50%;
    float: left;
    text-align: center;
    line-height: 64px
}
.horizontalScroll{color: orange}
<div class=wrapper>
    <div class=horizontalScroll>Scroll (x,y) to </div>
    <div class=verticalScroll>see me in action</div>
</div>

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

Tags:

Javascript