Radex
Radex

Reputation: 8577

Using scrollTop to detect scroll

I would like to log how much the user is scrolling a wrapper.

The following code does not work. I would like to know what am I doing wrong and how to fix it. Thanks!

const content = document.getElementById('content')
const wrapper = document.getElementById('wrapper').addEventListener('scroll', () => {
  console.log(content.scrollTop)
})
#wrapper {
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  width: 250px;
  height: 250px;
  overflow: auto;
}

#content {
  position: absolute;
  top: 0;
  left: 0;
  background-color: orange;
  width: 50px;
  height: 500px;
}
<div id="wrapper">
  <div id="content"></div>
</div>

Upvotes: 2

Views: 82

Answers (2)

AdminDev826
AdminDev826

Reputation: 330

To Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

scrollTop() : The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

$('#wrapper').scroll(function() {
  console.log($(this).scrollTop());
});
#wrapper {
  background-color: red;
  position: absolute;
  top: 0;
  left: 0;
  width: 250px;
  height: 250px;
  overflow: auto;
}

#content {
  position: absolute;
  top: 0;
  left: 0;
  background-color: orange;
  width: 50px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="content"></div>
</div>

Upvotes: 0

illiteratewriter
illiteratewriter

Reputation: 4323

It is not content.scrollTop, but wrapper.scrollTop.

Upvotes: 2

Related Questions