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

Arrange flex list items in vertical rows on smaller screens for a more organized layout

Struggling to have CSS flex list stagger text on two lines for smaller screens, but so far, my attempts have failed. I've tried using spans and br at various media queries, but nothing seems to work. Any assistance would be greatly appreciated. This ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Generating an array of quarter numbers and year based on the current date in Node.js using Moment.js - a simple guide

I need to generate an array of quarter numbers and year numbers based on the current timestamp in Node.js. For instance, if the current quarter is Q1 and the year is 2020, I want to create an array similar to the one below. quarters = ['Q2-2019' ...

Issue with Next.js app styles persisting on pages after page refresh

I am currently working on my first next.js project, transitioning from create-react-app, and I've encountered an unusual issue. When I refresh the home page, the CSS styles persist without any problem. However, if I navigate to a different page like " ...

Implementing customized line breaks in PHP using custom fields

My knowledge of PHP is quite limited, so I prefer to seek advice from experts before attempting anything I find online. I recently installed a customized billing field plugin in order to collect additional billing information during the checkout process. ...

The Disabled element does not exhibit effective styling

When we include the disabled attribute in the text element, the style does not work. Can you explain why? <input pInputText [style]="{'padding-bottom':'10px','padding-top':'10px','width':'100%&apos ...

Is there a way to change the images displayed in a JavaFXML Button?

I'm attempting to create a button that toggles between displaying an image of a red circle and an image of a blue circle when clicked. In my CSS, I've set up styles for the different states of the button: #button-debit { -fx-background-image ...

Testing the Router.push function using Jest and ReactHere is a guide on how

As a beginner in unit testing, I find it challenging to grasp how I can effectively test or mock a push from a router. <Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/> I am particularly concerned about testi ...

Having trouble getting the tailwindcss Google font link tag to apply properly

When I use the @import in the tailwind css file, it works fine. However, when I try to add the font using the <link> tag in _document.jsx, it fails to work properly. In Chrome dev tools, it shows that the classes are applied but the fallback font is ...

Can PhoneGap be used to create HTML5 applications from scratch?

Despite diligently searching through the PhoneGap website and their support group, I am still coming up empty-handed in my quest for an answer: My current project involves creating an application that functions as a pure HTML5 application, capable of runn ...

Is React capable of storing and recognizing images within its system?

As a junior developer, I find this aspect confusing. Specifically, does reusing the same image on multiple routes in React result in the user downloading it more than once in the browser? I am striving to understand whether using the same image repeatedly ...

Can CSS be used to create an animation effect with just this image?

Is it possible to incorporate a running image of "Pikachu" using CSS instead of creating a heavier GIF format? I have the image link and code below, but need assistance on how to implement it. Can you provide guidance? image: .pikaqiu_run { width: ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

An oversized image creates additional room

I currently have a board that consists of 3 blocks, with each block containing a grid of 25 squares. These squares are 40x40px in size with a margin around them, resulting in an overall size of 220px x 220px. Each square also has some space above and below ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

Conquering Bootstrap 3's Image Gallery Customizations

I am currently working with Bootstrap 3 RC1 and struggling to set up the image gallery properly. Issue 1 - The ul is adding unnecessary padding-left or margin-left. What do I need to do to eliminate this? Issue 2 - Each li is extending across the contain ...

How can triple nested quotes be utilized within Django templates?

Currently, I am attempting to utilize inline CSS and load an image as a background in a Django template. My goal is to include three quotes, however, I am unsure of the correct way to achieve this. Can anyone provide guidance on how to properly modify the ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

How come my div is taking on the height of something that isn't its direct ancestor?

I am in the process of creating a website that features a consistent design element of an inset border surrounding a block of content within a <div>. This inset border is achieved using LESS/CSS, and is contained within a separate <div class="inse ...

What is the best approach for adding text to an image using TCPDF?

I am trying to create dynvouchers PDF using TCPDF. However, I am facing an issue where the PDF generated does not include the username and password. Here is my code: $html = ''; $html .= '<table><tr>'; for ($a = 1; $a <= ...