Evans Evans - 5 months ago 10
Javascript Question

scrollTop of element always returns 0

Im trying to log how far down the page an element is, but in my console I keep getting 0.

window.addEventListener('scroll', function() {

var selector = document.getElementById("footer");

console.log(selector.scrollTop );

});


From reading about this there seems to be a webkit bug if the body has an overflow or height applied it. However Ive tried this in IE and Firefox, and with all my CSS disabled and I keep getting the same result.

Answer

Use offsetTop instead.

window.addEventListener('scroll', function() {

  var selector = document.getElementById("footer");

  console.log(selector.offsetTop);

});

Online demo - https://plnkr.co/edit/JdeFnB6IZodL0b74pO2S?p=preview

  • check the console output, iv'e set an interval to trigger the print

    enter image description here

Comments