-2

New to JavaScript. I'm trying to get a header element that disappears when scolling down, and appears when scrolling up.

Why isn't this selecting the <header> element?

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementsByTagName("header").style.top = "0";
  } else {
    document.getElementsByTagName("header").style.top = "-72px";
  }
  prevScrollpos = currentScrollPos;
} 


header {
    height: 72px;
    background-color: red;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    transition: top 0.2s ease-in-out;
    z-index: 200;
}

But if I add an ID to the <header> I can select it using the following

document.getElementById("navbar")

pilchard
  • 12,414
  • 5
  • 11
  • 23
user2991837
  • 626
  • 1
  • 8
  • 17
  • Does this answer your question? [How to get the value using getElementsByTagName](https://stackoverflow.com/questions/11947248/how-to-get-the-value-using-getelementsbytagname) – pilchard Sep 15 '20 at 11:56
  • Sorry don't understand that – user2991837 Sep 15 '20 at 11:59
  • Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Taplar Sep 15 '20 at 12:01
  • 1
    Sorry don't understand a word of it. The answer below answers my question – user2991837 Sep 15 '20 at 12:05

1 Answers1

2

.getElementsByTagName() returns an HTMLCollection which is like an array. You need to do this:

document.getElementsByTagName("header")[0].style.top = "0";

or use .querySelector() which accepts CSS selectors and returns the first element matched:

document.querySelector("header").style.top = "0";
Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100