Anas Latique
Anas Latique

Reputation: 408

Equivalent of window.scrollY for a div

What is the best way to detect how much a user scrolled Vertically in a div element using plain JS? These are snippets from my code:

html

<div id="blaaaa">
<!-- DIV CONTENT -->
</div>

js

document.getElementById('blaaaa').addEventListener('scroll', this.handleScroll);

handleScroll(e) {
  // I want to use an equivalent of window.scrollY but for a single div element
  var scrolled = window.scrollY;
  // ...
},

How can I do that?

I appreciate your answers. Happy Holidays!

Upvotes: 11

Views: 13463

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22351

if the question is how best to detect how much a user has scrolled vertically in a div element using JS, which for me also means having easy-to-read code, then this is it (but that's my personal opinion).

const scrollVal = document.getElementById('scroll-val')
  ,   blaaaaElm = document.getElementById('blaaaa')
  ;
blaaaaElm.onscroll=e=>
  {
  scrollVal.textContent = blaaaaElm.scrollTop;
  }
#blaaaa {
  width: 100px;
  height: 100px;
  overflow-y: scroll;
  background-color: palegoldenrod;
}
<p id="scroll-val">0</p>

<div id="blaaaa">
  <p>....</p>
  <p>....</p>
  <p>....</p>
  <p>....</p>
  <p>....</p>
  <p>....</p>
  <p>....</p>
  <p>....</p>
</div>

Upvotes: 1

soywod
soywod

Reputation: 4520

Use scrollTop:

document.getElementById("container").addEventListener("scroll", evt => 
  console.log(evt.target.scrollTop)
)
#container {
  height: 300px;
  width: 300px;
  background: cyan;
  overflow-y: scroll;
}

#content {
  height: 1000px;
  width: 100%;
}
<div id="container">
  <div id="content"></div>
</div>

Upvotes: 17

Related Questions