Hadi Zouhbi
Hadi Zouhbi

Reputation: 71

Why isn't my span changing color on scroll

HTML that is needed to know

<section class="home" id="home">
            <div class="max-width">
                <div class="home-content">
                    <div class="text-1">Hello, my name is</div>
                    <div class="text-2">Hadi Zouhbi</div>
                    <div class="text-3">And I'm a <span id="headSpan">Developer</span></div>
                </div>
            </div>
        </section>

Here is the needed CSS

.sticky {
  padding: 30px 0;
  background-color: crimson;
}

.stickyHeadSpan {
  color: #fff;
}

Here is the javascript code that is needed

window.addEventListener('scroll' , function(){
    if(window.scrollY > 20){
        const navbar = document.querySelector('.navbar')
        const headSpan = document.querySelector('span')
        navbar.classList.add('sticky')
        headSpan.classList.add('stickyHeadSpan')
    } 
})

window.addEventListener('scroll' , () => {
    if(window.scrollY === 0) {
        const navbar = document.querySelector('.navbar')
        navbar.classList.remove('sticky')
    }
})

I tried getting the span by the id and still did not work , whenever I scroll down the span is not changing color to white , did I make a mistake somewhere ? I also tried using just span so no id or class and it still did not work , it is really strange . Is there any rule that makes this not work ? I am a beginner at Javascript so I hope you can help me fix this.

Upvotes: 1

Views: 77

Answers (1)

Brijesh Kalkani
Brijesh Kalkani

Reputation: 851

window.addEventListener('scroll', function() {
    
    if (window.scrollY > 20) {
        const navbar = document.querySelector('.home');
        const headSpan = document.querySelector('span');
        navbar.classList.add('sticky');
        headSpan.classList.add('stickyHeadSpan');
    }
})

window.addEventListener('scroll', () => {
    
    if (window.scrollY === 0) {
        const navbar = document.querySelector('.home')
        navbar.classList.remove('sticky')
    }
})
.wrapper{
    height: 200vh;
}

.sticky {
    padding: 30px 0;
    background-color: crimson;
    position: sticky;
    top: 0;
    left: 0;
}

.stickyHeadSpan {
    color: #fff;
}
<div class="wrapper">
  <section class="home" id="home">
          <div class="max-width">
              <div class="home-content">
                  <div class="text-1">Hello, my name is</div>
                  <div class="text-2">Hadi Zouhbi</div>
                  <div class="text-3">And I'm a <span id="headSpan">Developer</span></div>
              </div>
          </div>
  </section>
</div>

Upvotes: 6

Related Questions