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 badges2 Answers
Reset to default 17Use 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>