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

Creating a responsive navigation menu by converting overflowing menu items into a dropdown list

I'm currently designing a menu that contains multiple list items. I would like the overflowing li's to collapse and display in a dropdown when resizing the browser to smaller screens, such as laptops and tablets. Original Menu. Responsive view ...

Menu options displayed with the help of HTML5 tags

Currently, I am experimenting with creating an interactive HTML5 dropdown menu in my spare time. While researching on W3Schools about dropdown menus, I noticed that all of them utilize CSS classes and id's for styling. This is a snippet of the HTML c ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Executing the command in the Windows Command Prompt by utilizing an HTML button

When a button on my HTML page is clicked, I want to execute the command python abc.py in the Windows command prompt. The python file is stored at C:/abc.py. I'm looking for guidance on how to code the HTML page to achieve this functionality. Any assis ...

Tips on displaying an avatar above and outside the boundaries of a background element using Chakra UI

They say a picture is worth more than a thousand words, and in this case, it holds true. The best way to illustrate what I'm trying to accomplish is through the image linked below. https://i.stack.imgur.com/5WvkV.png I envision having the avatar po ...

Learning to extract information from elements within components in a flexbox using Angular

Is there a way to access the element width of child components within a parent component that utilizes flex box? I am hoping to determine if the list is overflowed so I can adjust the visibility of elements accordingly. If an overflow occurs, I would like ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

"TailwindCSS opts for the inclusion of prefexied utilities instead of relying

Trying to set the height of the div to h-2, with a class that includes height animation on medium devices. The issue is that even though h-2 should be used on mobile, tailwindcss still uses h-20 instead. Any thoughts on why this may be happening? Here i ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

JQuery jqx validation is experiencing some issues

Utilizing jquery plugins and widgets from jqx for basic form validation in my ruby-on-rails application has proven to be very helpful. Here is a simple example of an HTML form: <form id="newForm"> <input type="text" id="name"/> < ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

Looking to scan through a directory of .html files in Node.js to find specific element attributes?

Imagine trying to tackle this task - it's like reaching for a needle in a haystack. Picture a folder containing a static website, complete with images, stylesheets, and HTML files. My Node application needs to dive into this folder and extract only th ...

Eliminate any empty spaces between the HTML tags

Is there a way to remove spaces between characters inside HTML tags? For example <option value="0" title="Advertising / Promotional Charges">Advertising / Promotional Charges</option> I tried using this code .replace(/\>\s+&bs ...

Only display one div element when in print mode, hiding all others

My print style CSS code includes the following: * { display:none; } #printableArea { display:block; } Initially, I anticipated that this CSS would hide all elements except for the printableArea. Surprisingly, everything on the page became hidden when ...

What would you suggest as a more effective method for preventing content overlap during multi uploads?

Recently, I was working on a Wordpress site and used the Ninja Forms plugin to create a form. One of the challenges I encountered was styling the file upload button. After some research, I came across a tutorial that provided a great solution that worked a ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

How to use puppeteer to extract images from HTML that have alt attributes

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1">&l ...