What could be the reason my span is not altering color as I scroll?

Important HTML Knowledge

<section class="home" id="home">
            <div class="max-width">
                <div class="home-content">
                    <div class="text-1">Hey there, my name is</div>
                    <div class="text-2">John Doe</div>
                    <div class="text-3">And I'm a <span id="headSpan">Coder</span></div>
                </div>
            </div>
        </section>

CSS Requirements

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

.stickyHeadSpan {
  color: #fff;
}

Essential JavaScript Code

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've been struggling to change the span text color to white when scrolling. I tried selecting by ID and even without any identifier but it didn't work. Could there be a rule causing this issue? As a beginner in Javascript, I would appreciate your assistance in fixing this problem.

Answer №1

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">Welcome, my name is</div>
                  <div class="text-2">John Doe</div>
                  <div class="text-3">And I'm a <span id="headSpan">Designer</span></div>
              </div>
          </div>
  </section>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for storing user-provided document names in Firestore database entries?

I'm encountering an issue with my API while trying to utilize Firestore for inputting data for login and registration via the API. The problem arises when attempting to add a document entry in the database with the user's input email during regis ...

What causes the scope to shift when incorporating a Lazy function within the module pattern in JavaScript?

Implementation 1: Working code in normal var foo1 = function() { var t1 = new Date(); console.log("initialize - one time only " + this); foo1 = function() { console.log("Executes every time after initializing (initialize should not e ...

Adjusting the angular routerLink based on an observable

When working with HTML in Angular, I am looking for a way to use an <a> tag that adjusts its routerlink based on whether or not a user is logged in. Is it possible to achieve this functionality within a single tag? <a *ngIf="!(accountService ...

Submitting quiz responses through a PHP based form

I am currently facing an issue with integrating forms and a quiz on my website. Individually, both work fine but when combined, they do not function as expected. Specifically, the quiz itself operates correctly, however, it fails to send the results via P ...

effective method for iterating through JSON data using JavaScript or jQuery

Upon receiving a JSON object from the server, it looks like this: { "0": { "id": "1252380", "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?", ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...

Ensure the accuracy of submitted form information

I am seeking to enhance the validation process for my form, which is already using jquery.validate.min.js for validation. I want to incorporate another layer of validation by making an ajax call to my MySQL database to check if the email address provided i ...

Tips for aligning text to the right within a div using the "justify" text-align property

I want the final sentence of my content to be aligned to the right side while the rest remains justified. I attempted using a <span> within a <p> tag, but it did not work as expected: span.activity-conclusion { font:22px 'Open Sans ...

Executing an on-click event on a button in PHP

I've been developing a learning site that involves teachers, students, and different subjects. To organize the registration process, I decided to separate the teacher and student registration pages since they input data into different tables in the da ...

Connecting JavaScript and HTML in EclipseWould you like to know how to link

After completing the Rock Paper Scissors exercise on Codecademy, I wanted to transfer it to my Eclipse IDE. The code worked perfectly on the Codecademy platform, so I copied everything and created a .js workspace in Eclipse to paste it there. Now, my ques ...

Prevent the Rain from descending

Looking for a way to toggle a particle emitter on or off, I've encountered memory leaks with my Reactjs code that generates rain/snow particles using the canvas element. Despite attempts to stop the animation properly, it seems to be projecting a new ...

The element remains stationary and does not shift positions

My form is not centralizing properly, it seems to be stuck to the left side of #wrapper. I've tried adjusting margin-top but it doesn't seem to affect its horizontal position at all. I've played around with different values for margin and ev ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Text displayed in a pop-up when hovering

I'm in search of suggestions for creating a text pop-up that displays when the mouse hovers over specific text. After researching numerous websites, I haven't found exactly what I need. Currently, I have a table with headers at the top and I woul ...

To ensure proper functionality, make sure that Python Selenium's Geckodriver is correctly

I want to automate form filling using Selenium. Below is the HTML code for the form: <!DOCTYPE html> <html> <body> <h2>Text input fields</h2> <form> <label for="fname">First name:</label><br& ...

Determine the latest date within each group and display the corresponding output value

I am seeking a way to showcase only the most recent value for each group. For example, in the CSV data provided below, the total amount of Bagels in the Cinnamon Raisin variety were collected during three different sampling periods: May 2017, March 2017, ...

Utilizing Kendo for Dynamic HTML Element Connection

Currently, I am facing a situation where I have three HTML elements. The first is a textbox labeled shipToAddress, the second is another textbox called deliverToAddress, and finally, there is a checkbox named sameAsShipToAddress. In the background, there ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...