最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Equivalent of window.scrollY for a div - Stack Overflow

programmeradmin4浏览0评论

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!

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!

Share Improve this question asked Dec 23, 2019 at 16:53 Anas LatiqueAnas Latique 4081 gold badge7 silver badges16 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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>

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>

发布评论

评论列表(0)

  1. 暂无评论