Sophy Chann
Sophy Chann

Reputation: 3

How can I show second header when scroll down 60px?

.nav-header2{
         background: purple;
         display: flex;
         justify-content: center;
         align-items: center;
}
.header2-container{
        width: 68vw;
         height: 60px;
         padding: 0 2vh;
         border: 1px solid red;
         border-radius: 0.5rem;
         display: flex;
         justify-content: space-between;
         align-items: center;
}
.nav-header1{
         background: lightblue;
         display: flex;
         justify-content: center;
         align-items: center;
}
.header1-container{
        width: 68vw;
         height: 60px;
         padding: 0 2vh;
         border: 1px solid blue;
         border-radius: 0.5rem;
         display: flex;
         justify-content: space-between;
         align-items: center;
}
  <!--header2 -->
  <nav class="nav-header2">
      <div class="header2-container">
          <h1>header2<h2>
      </div>
  </nav>
  
  <!-- header1 -->
  <nav class="nav-header1">
      <div class="header1-container">
          <h1>header1<h2>
      </div>
  </nav>

I have two headers for my web page. I named header1 and header2.

I want to show header2 when scrolling down bigger than 60px and hide when scrolling is smaller than 60px.

if (scroll down bigger than 60px){ show header2 }else{ still show header1 }

I have tried many time, But I can't succeed. Please help Thank you so much!

Upvotes: 0

Views: 156

Answers (1)

Mohamad
Mohamad

Reputation: 608

Please check the code below when you scroll 60px and more the header 1 disappear and header 2 appear

window.addEventListener("scroll", () => {
  if (scrollY >= 60) {
    document.querySelector(".headerOne").style.display = "none";
    document.querySelector(".headerTwo").style.display = "block";
  } else {
    document.querySelector(".headerTwo").style.display = "none";
    document.querySelector(".headerOne").style.display = "block";
  }
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 60px;
  background-color: gray;
}

.headerOne,
.headerTwo {
  position: fixed;
  top: 0;
  left: 0;
  background-color: white;
  width: 100%;
  font-size: 20px;
  text-align: center;
  height: 60px;
}

.headerTwo {
  display: none;
}
<div class="headerOne">header 1</div>
<div class="headerTwo">header 2</div>
<section>section</section>
<section>section</section>

Upvotes: 1

Related Questions