0

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";
  }

});
1
  • That's because box.scrollTop always returns 0. Add console.log(box.scrollTop); above your if() statement and you will see the result of box.scrollTop in the console. Commented Jun 4, 2017 at 17:00

1 Answer 1

3

You have to get the scrollTop on the document body element, not on your box. In your case, box.scrollTop will always be 0.

Replace this:

  if (box.scrollTop > 0) {
    box.style.background = "blue";
  }

with this:

  if (document.body.scrollTop > 0) {
    box.style.background = "blue";
  }

Also note, that as of now it's better to use window.pageYOffset as document.body.scrollTop is deprecated in strict mode. Read this to learn more about scroll detection on the entire window.

Demo: https://codepen.io/anon/pen/mwdZwL

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.