Is there a way to implement a scrolling feature that specifically identifies an h1 element, and subsequently alters the color of said element upon reaching a distinct section?

Currently, my function changes the color to black when the scroll number reaches 100. However, I am looking to target the JavaScript so that it changes the color to black when the scroll reaches a specific section designated by a p tag. My code is almost there, but I need help altering the if statement to pinpoint specific sections rather than relying on a number value?

<!-- HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scrolling Function Practice</title>
</head>
<body>
<header>
            <h1 class='test-title'>Testing title</h1>
        </header>
 
        

    <br>

        <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Magni excepturi error facere sed quas repellat perferendis, 
        enim cumque, voluptatem mollitia porro consectetur dicta officiis itaque, quae adipisci accusamus quibusdam amet eligendi. 
        Ad delectus iure exercitationem accusamus ea nihil magni doloribus, inventore aut molestias repudiandae hic non in asperiores 
        dolor! Repellat blanditiis accusantium rem iure, molestias doloremque quidem. Facere nisi libero error aut hic tempora quidem 
        voluptate, omnis, nihil molestias, animi quia distinctio? Vel beatae, at dolore, laboriosam rem voluptatibus sunt illo obcaecati
        modi iure sed odio voluptatum, numquam accusantium quibusdam tenetur velit aliquid! Ad animi sunt ratione suscipit totam tenetur 
        quia exercitationem excepturi doloribus vero nostrum, sapiente alias iste nam doloremque voluptatum consectetur reiciendis omnis 
        tempora? Esse quaerat molestias hic beatae ipsum, recusandae odio nobis sit quo in veniam aperiam, itaque facilis rerum eum. 
        Exercitationem architecto nulla dolor nemo eius neque ipsam omnis provident porro laborum eaque, totam quos. Obcaecati totam 
        doloribus recusandae aliquam quisquam consequuntur soluta impedit dolorum quam at? Aliquid, reiciendis. Eveniet, earum aliquid 
        sapiente quo voluptates velit nemo, distinctio architecto sint tenetur itaque! Dolore, sapiente debitis. Dolorum tempore, sunt 
        quam eos praesentium molestiae animi delectus architecto ipsa voluptate repudiandae odio error nulla. Nihil, accusamus aperiam! 
        Magni iure ea nulla veniam, provident quae ex nobis saepe veritatis dolor! Minus omnis totam quasi nam illum explicabo non ipsum 
        quibusdam iste sed facere officia, quia, minima sint debitis. Sequi consectetur assumenda tempore autem hic nihil alias! Illum natus 
        totam reiciendis adipisci voluptatibus nostrum! Ratione illo nulla provident, laborum quaerat voluptas.
    </p>
  


    <!-- CSS -->
<style>
    /*CSS to set position of title*/
        body {
            min-height: 1400px;
        }

        p {
            color: black;
            margin-top: 700px;
        }
    
        .test-title {
            position: fixed;
            color: white;
            background-color: darkblue;
            margin-bottom: 100px;
            transition: all 0.5s;
            z-index: 100;
        }
        
        .test-title.active {
            color: black;
            transition: all 0.5s;
        }

    </style>
    
    <!-- JavaScript -->
    <script>
        const titleEffect = document.querySelector('.test-title');
        
        
        //scroll function
        window.onscroll = function() {
            let top = window.scrollY;
            console.log(top);
            if (top >= '100') {
                titleEffect.classList.add('active');
            } else {
                titleEffect.classList.remove('active');
            }
        } 
    </script>
</body>
</html>

Answer №1

If you're searching for a way to dynamically change the color of your title element based on the visibility of a specific <p> tag, then you should explore the intersection observer API.

This API allows you to define a callback function that will trigger when the specified <p> tag comes into view, giving you the ability to update the color of your title element accordingly.

For more information and detailed documentation, you can visit this link: here

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 best way to modify the value of an external variable within a promise?

var isError = false; savedata.ingredients.split(',').reduce(function(p, ing) { return p.then(function() { return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId }); }); }, Promise.resolve()).catch(function( ...

Upload button allowing multiple values to be uploaded as a single file

I'm currently facing an issue with my list of values and upload buttons. The file upload functionality is working correctly, but the problem arises when I try to upload a file for any item in the list - it always uploads for the first item only. Here ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

Integrate Chrome extension using code

Is there a way to programmatically load a Chrome extension? Can it be done using web driver with external extension preferences, or perhaps through JavaScript or another scripting language? ...

Is there a way to submit HTML form data using the action attribute without triggering a redirection to a different page?

I am currently working with Angular and Plaid. My goal is to submit a form that sends the public_token to /authenticate using the 'action' attribute in the HTML form. How can I achieve this without being redirected to another page? Step 2: Easy ...

Ajax ensures that the site stays active and responsive

Struggling to understand how to make this code work. var request; if(window.XMLHttpRequest){ request= new XMLHttpRequest(); }else{ request = new ActiveXObject("Microsoft.XMLHTTP"); } var handleStateChange = function () { switch (request.re ...

The Cy.visit() function in Cypress times out and bypasses tests specifically when navigating to a VueJS web application

Having trouble with the Cypress cy.visit() function timing out and aborting tests on a VueJS Web Application? It seems to work fine when opening other non-VueJS sites. Below is my basic configuration setup: [package.json] "dependencies": { "cypres ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

Retrieve information following an Ajax call inside a pre-designed template

Upon rendering a page with data put together by EJS, the goal is to refresh a section (thirdRow) of the page whenever the user submits new data. The refreshed section should display both the newly submitted data and the existing data. Although I have obtai ...

What is the most effective method for assessing a service using angular?

As a beginner in angular testing, I am eager to start creating tests for my service. However, I have encountered an issue where my service (foo) injects another service (bar) in its constructor. Should I create a mock for bar? Do I need to mock every func ...

Generate a new number every time you click, ensuring that it will never be repeated

Is there a way to randomize a number on clicking a button without repeating the same numbers? $('button').click(function(){ var randomNumber = Math.floor(Math.random() * 100); } <button>Click me</button> ...

The correct way to extract a jwt token from headers and integrate it into an express application

After successfully implementing both the frontend and backend in express.js with authentication and authorization using JWT, I have confirmed that the JWT token is being properly set upon login. You can see the auth-token key in the image below: https://i ...

To ensure the react page is not rendered until the script has finished executing, follow these steps in React

Upon fetching data from an API using my script, I encounter a challenge where the react page loads before the script finishes loading. As a result, I end up with a page lacking necessary information and have to refresh in order to see the updates. The ma ...

Using jQuery to create Vertical Tabs that showcase tab content in an inline-block format

When using jQuery tabs, I recently switched to vertical tabs and noticed that the content is not positioned within the space after the tabs. Instead, it is placed inside a container div with a margin, giving the appearance of being contained within that bo ...

What's the best choice for me: useState, useRef, or useMemo?

I am facing a situation where I need to retain the result of a function throughout the lifecycle of a component (this value should remain constant). Take a look at the following example const UniqueIdView = () => { const [uniqueIdState1] = useState ...

Tips for invoking a Server-Side Function from within a JavaScript Function

When my button is clicked, it triggers the following code: protected void Button6_Click(object sender, EventArgs e) { Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true); } In addition, ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Photoshop script for verifying layer names

I am currently working on a script to verify my images. Here are the criteria I need to validate: Determine the number of layers and pathItems in the document - relatively straightforward. Identifying the names of 3 specific layers: I have hit a roadblock ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...