Jan Turoň
Jan Turoň

Reputation: 32912

Get the scroll position in a div

This must be something trivial I am missing, I really can't figure it out:

I am gazing here for quite a long time: scrollTop

I am playing here for quite a long time: jsFiddle

And I am about to bring some human sacrifice to get the answer why the hell is scrollTop always zero?

HTML

  <div style="height: 200px; border: 1px solid black; overflow: scroll">
    <div id="x" style="height: 100px; background: #EEE;"></div>
    <div style="height: 500px"></div>
  </div>

JS

  var x = document.getElementById("x");
  x.parentNode.onscroll = function() { console.log(x.scrollTop); }

Please don't jQuery me.

Upvotes: 1

Views: 165

Answers (1)

Anoop
Anoop

Reputation: 23208

Because you are using wrong element to get topScroll JSFIDDLE it should be x.parentNode.scrollTop instead of x.scrollTop

  var x = document.getElementById("x");
     x.parentNode.onscroll = function() { console.log(x.parentNode.scrollTop);
  }

Upvotes: 1

Related Questions