I'm trying to achieve something in vanilla JS and it's not playing ball. I have an element I want to change color after a certain scroll length, but when I use addEventListener('scroll', function) etc it's not working, but I'm not getting any errors in my console.
Any help would be awesome.
Emily
The code is below and I have a pen here: https://codepen.io/emilychews/pen/eRYwzm
HTML
<div class="box"></div>
CSS
body {height: 200vh;}
.box {
width: 200px;
height: 200px;
background: red;
}
JAVASCRIPT
var box = document.getElementsByClassName('box')[0];
window.addEventListener('scroll', function() {
if (box.scrollTop > 0) {
box.style.background = "blue";
}
});
box.scrollTopalways returns0. Addconsole.log(box.scrollTop);above yourif()statement and you will see the result ofbox.scrollTopin the console.