Nello
Nello

Reputation: 1755

scrollTop always returns 0 here

I want the cover title to move up as I scroll but currently I cant get the scrollTop to work. Using vanilla JavaScript.

Here is my code:

window.onload = function(){
  var coverTitle = document.querySelectorAll('.cover-title');
  window.addEventListener("scroll", function(){
    console.log(coverTitle.item(0).scrollTop);
  });
};
.cover{
  width: 100%;
  height: 500px;
  background-image: url('img/cover.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  position: relative;
}

.cover h1{
  color: white;
  position: absolute;
  font-family: serif;
  top: 70%;
  left: 10%;
}
<div class="cover">
  <h1 class="cover-title animate fadeIn">Some text</h1>
</div>

Upvotes: 0

Views: 3486

Answers (1)

squiroid
squiroid

Reputation: 14027

Here according to doc

The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward. An element's scrollTop is a form of distance measurement regarding an element's top to its topmost visible content. When an element content does not generate a vertical scrollbar, then its scrollTop value defaults to 0.

Doc: https://developer.mozilla.org/en/docs/Web/API/Element/scrollTop

The very first point states that.

If the element can't be scrolled (e.g. it has no overflow or if the element has a property of "non-scrollable"), scrollTop is set to 0.

Your element don't have any overflow property so it's naturally set scrollTop to 0.

Upvotes: 2

Related Questions