Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a reference site () that demonstrates text color change while scrolling - I want to implement something similar :)

P.S. Kindly advise using JavaScript, thanks!

I've tried searching for solutions, but haven't found anything satisfactory yet :(

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="/b/cs.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d489cdc7cbcad7e4958a9d8a95">[email protected]</a>/font/bootstrap-icons.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>

    <section class="section-top active" id="s1">
        
        <div class="details">
            <div class="top">
                <h2>Faxraddin</h2>
                <div class="lists">
                    <div class="nav-btn" id="nav-icon1" onclick="document.getElementById('nav-icon1').classList.toggle('open')">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
                <div class="hide-it">
                    <div class="hide1">
                        <div class="p1">
                            <a class="hide1-btn">My Work</a>
                            <a class="hide1-btn">My Shelf</a>
                            <a class="hide1-btn">My Resume</a>
                        </div>
                         
                        <div class="p2">
                            <a class="hide-span">SAY HELLO</a>
                            <a class="hide-span"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a00040905030903022a0d070b030644090507">[email protected]</a></a>
                            <a class="hide-span">t/me.com</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="first-info">
                <div class="first-sec">
                    <h1>Frontend</br> Developer.</h1>
                    <h3 class="profession-info">I like to craft solid and scalable frontend products with great user experiences.</h3>
                </div>
                <img class="my-img" src="/b/images/Screenshot 2022-11-04 at 19.35.20.png">
            </div>

            <div class="some-info">
                <div class="a1">
                    <span>Highly skilled at progressive
                enhancement, design systems &
                UI Engineering.
                    </span>
                    <span>Over a decade of experience
                building products for clients
                across several countries.
                    </span>
                </div>

                <div class="btn-container">
                    <ul>
                        <a class="a" href="#s1"><div class="btn"></div></a>
                        <a class="a" href="#s2"><div class="btn"></div></a>
                        <a class="a" href="#s3"><div class="btn"></div></a>
                        <a class="a" href="#s4&...

Answer №1

If you're looking to track visibility and make changes based on it, consider using an intersection observer. This handy tool allows you to monitor a target element and trigger actions when it enters or exits the viewport.

I've put together a simple demo showcasing this functionality. In this example, we're observing 'section two' - changing its text color to purple when it's in view, and reverting back to black when it's out of sight.

const title = document.querySelector('.topbar__title');
const sectionOne = document.querySelector('.section--one');
const sectionTwo = document.querySelector('.section--two');

const observer = new IntersectionObserver((entry, observer) => {
  entry[0].isIntersecting > 0 ?
    title.style.color = sectionTwo.getAttribute('data-color') :
    title.style.color = sectionOne.getAttribute('data-color')
});

observer.observe(sectionTwo);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.topbar {
  position: fixed;
  top: 0;
  left: 0;
  padding: 1rem;
  width: 100%;
  background-color: white;
}

.section {
  height: 150vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.section--one {
  background-color: white;
}

.section--two {
  background-color: rgb(255 0 0 / 5%);
}
<div class="topbar">
  <h1 class="topbar__title">Title</h1>
</div>

<section class="section section--one" data-color="black">
  <h2>Section One</h2>
</section>

<section class="section section--two" data-color="purple">
  <h2>Section Two</h2>
</section>

You can expand on this by monitoring multiple sections or applying class changes instead of directly altering styles with JavaScript. Remember, this is just a basic illustration...

For more detailed insights about Intersection Observers, check out MDN's guide

Answer №2

Click this link to view the code: Visit Code

<html>
<head>
    <title>Javascript Scroll Background Change</title>
</head>

<body>
    <h1>STAGE1</h1>
    <div id="stage1">
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis, lectus ac efficitur congue, urna enim tincidunt metus, eget mattis purus nibh non tellus.
        </p>
        <p>Additional content here...</p>
        <p>More content goes here...</p>
        <p>Extra details...</p>
        <p>And more...</p>
    </div>

    <h1>STAGE2</h1>
    <div id="stage2">
        <p>
            Sed pretium orci vel neque vestibulum, et sagittis mi accumsan. Aliquam eu consequat justo. Cras elementum vehicula libero at gravida.
        </p>
        <p>Additional content here...</p>
        <p>More content goes here...</p>
        <p>Extra details...</p>
        <p>And more...</p>
    </div>

    <h1>STAGE3</h1>
    <div id="stage3">
        <p>
            Morbi sapien ex, fermentum eu condimentum quis, accumsan in erat. Duis pellentesque magna ac magna ultricies malesuada.
        </p>
        <p>Additional content here...</p>
        <p>More content goes here...</p>
        <p>Extra details...</p>
        <p>And more...</p>
    </div>

    <h1>STAGE4</h1>
    <div id="stage4">
        <p>
            Nullam dapibus mauris at odio pulvinar tempus. Fusce vitae varius nisl. Ut tempor risus a diam porttitor molestie.
        </p>
        <p>Additional content here...</p>
        <p>More content goes here...</p>
        <p>Extra details...</p>
        <p>And more...</p>
    </div>

    <h1>STAGE5</h1>
    <div id="stage5">
        <p>
            In hac habitasse platea dictumst. Ut blandit eros velit, id ornare nunc interdum sed. Donec nec cursus purus, non facilisis dui.
        </p>
        <p>Additional content here...</p>
        <p>More content goes here...</p>
        <p>Extra details...</p>
        <p>And more...</p>
    </div>

    <script
        src="https://code.jquery.com/jquery-3.6.1.min.js"
        integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
        crossorigin="anonymous"></script>

    <script>
        function changeBackground(color) {
            document.body.style.background = color;
        }

        // changeBackground("#000");

        var position1 = $("#stage1").offset();
        var position2 = $("#stage2").offset();
        var position3 = $("#stage3").offset();
        var position4 = $("#stage4").offset();
        var position5 = $("#stage5").offset();

        $(window).scroll(function (event) {
            var scroll = $(window).scrollTop();
            // Do something

            console.log(scroll);

            if (scroll == 0) {
                changeBackground("#FFF");
            }
            else if (scroll > position1['top'] && scroll <= position2['top']) {
                changeBackground("red");
            }
            else if (scroll > position2['top'] && scroll <= position3['top']) {
                changeBackground("blue");
            }
            else if (scroll > position3['top'] && scroll <= position4['top']) {
                changeBackground("yellow");
            }
            else if (scroll > position4['top'] && scroll <= position5['top']) {
                changeBackground("brown");
            }
            else if (scroll > position5['top']) {
                changeBackground("green");
            }
        });
    </script>
</body>

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

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

Adjust the text size of Twitter Bootstrap on mobile screens

I recently started using Twitter Bootstrap. I am currently hiding certain <tr> elements on phone screens by utilizing the class="hidden-phone". However, I am now looking to resize the displayed text to better fit the screen. Is there a way to adjus ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

What is the best way to retrieve the "value" property of an <input> element in HTML?

Imagine there is an <input> element. When using jQuery to get the attributes of this element, I have written the following code: console.log($("#radio").attr("type")); console.log($("#radio").attr("value")); <script src="https://cdnjs.cloudflar ...

Text located incorrectly beside image within container box

Below is the HTML code that defines a box containing title text and an image. <div id="about"> <div id="title"> <h3><b>About</b></h3></div> <div id="text"><p>Text</p></div> <div id="img ...

Creating a JSON array using looping technique

I am attempting to construct a JSON array using a loop where the input className and value will serve as the JSON obj and key. However, I am facing difficulties in creating one and cannot seem to locate any resources on how to do so. Below is an example sn ...

Best practices for locating unique symbols within a string and organizing them into an array using JavaScript

Here is an example string: "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>" The characters A, B, C, and so on are variables, and their count is not fixed. Can you determine how many ...

Adjust image placement when resizing the window or rotating a mobile device

When the window is maximized or the phone is in portrait position, the magnifying glass stays in its place. However, when I resize the window or rotate the mobile phone, the position of the magnifying glass changes. I've tried using different units ...

Are there any special CSS hacks that only work for IE8?

When it comes to Internet Explorer 8 (IE8), my preference is to utilize the following CSS: color : green; I am looking to implement a hack that exclusively impacts IE8, without affecting IE9, IE6, and 7. ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

When navigating within a page, Firefox shows {{ }} tags while Chrome does not in AngularJS

After experimenting with various techniques, I managed to successfully hide the content section upon initial page load. However, when navigating within the page, the tags still appear. Any suggestions on how to resolve this issue? You can view the proble ...

Finding text outside of a HTML tag with jsoup

I am working with the following HTML code: Data <div class="alg"></div> <div class="alg"></div> Pepsi 791 <div class="alg"></div> <div class="alg"></ ...

Transmit information to PHP via JSON with Cross Domain communication

My code is server1 and PHP code is server2. These servers are not connected. What issues can arise from this setup? var req = new XMLHttpRequest(); req.open("POST", "http://www.example.com/form/data.php", true); req.setRequestHeader("Content-type", "ap ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

Troubles with basic jQuery hide and show functionalities

Hey there! I've been working on a project for the past couple of days and I'm having trouble with creating a slider effect using jQuery hide and show. It's strange because my code works perfectly fine with jquery-1.6.2.min.js, but when I swi ...

Is an input field/text area necessary for the traditional copy to clipboard feature?

I needed to copy a section of text enclosed within an anchor tag to the clipboard. Following suggestions found online, I implemented the code below: HTML: <div class="organizer-link"> <i class="fa fa-link" id="copylink"></i> <a href ...

Struggling to close modal popup after submitting form

click here for imageCurrently, I am working with the bootstrap modal plugin to create an inquiry form. The issue I am facing is that even though I am using the "ng-submit" directive to save the form details, when I click submit, the form submits successful ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

RTK Query may sometimes encounter undefined values when fetching data

I am new to using Redux and facing an issue while trying to display data in a Material UI Select. When I try to show the user's name, it works perfectly, but when I do the same for the partner's data, they appear as undefined. In my server index ...