mizech mizech - 29 days ago 3
Javascript Question

Why does scrollTop property of element stay 0 when scrolling?

I'm trying to use the

scrollTop
property in a project.

But it doesn't matter what I do: It always returns me
0
. I've working with Chrome. Tried Firefox too with the same result.

I have made this demo:



var wrap = document.querySelector('.wrap');

wrap.addEventListener('scroll', function() {
var sub = document.querySelector('.sub');

console.log(sub.scrollTop);
});

body {
background-color: white; }

.wrap {
padding: 10px;
border: 3px solid white;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 600px;
height: 400px;
overflow: scroll; }

.sub {
height: 1200px;
width: 200px;
background: linear-gradient(orange, green, blue, red); }

<div class="wrap">
<div class="sub"></div>
</div>





In Chrome

What do I wrong?

Respectively: Why do I get these obviously wrong value back?
I would expect approximately
800
when it is scrolled to the very bottom.

Answer

The scrollTop property should be read from the actual scrolling element, .wrap in your case, not a child of that element.

Instead of:

console.log(sub.scrollTop);

Try:

console.log(wrap.scrollTop);