What is the best way to accomplish a smooth transition of background colors similar to this design

I was browsing different websites and stumbled upon this amazing background color transition that caught my attention. I really liked it and now I want to create something similar on my own website. Despite my best efforts, I haven't been able to achieve the desired effect.

Specifically, I aim to change the color as a div appears on the screen rather than when it reaches the top of the browser window.

I'm wondering how I can accomplish this?

Here is an example of what I've attempted:

$(window).on("scroll touchmove", function () {
    if ($(document).scrollTop() >= $(".homeContainer").position().top) {
        setTimeout(function () {
            $('.transGrow').addClass('grow');
        }, 275);
        $('body').addClass('landing');
        $('header').addClass('landing');
        $('body').removeClass('quickLinks');
        $('header').removeClass('quickLinks');
    }
    ;
    if ($(document).scrollTop() > $(".slide1").position().top) {
        $('body').addClass('quickLinks');
        $('header').addClass('quickLinks');
        $('body').removeClass('landing');
        $('header').removeClass('landing');
        $('body').removeClass('aboutUs');
        $('header').removeClass('aboutUs');
    }
    ;
    if ($(document).scrollTop() > $(".slide2").position().top) {
        $('body').addClass('aboutUs');
        $('header').addClass('aboutUs');
        $('body').removeClass('quickLinks');
        $('header').removeClass('quickLinks');
    }
    ;
});
.landing
{
    background-color:#F8BBD0;
}
.quickLinks {
    background-color: #9575CD;
}
.aboutUs{
    background-color: #9CCC65;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="homeContainer">
<div class="container-fluid slide slide1 section-basic" id="quickLinks">
        <div class="rows">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" data-aos="fade-up">
                <h1 class="text-uppercase text-center heading-basic">Quick Links</h1>
                <hr class="transGrow">
            </div>
        </div>
        <div class="rows">
            <div class="scrollable-cover col-lg-4 col-md-4 col-sm-4 col-xs-4" data-aos="fade-left">
                <a href="#">
                    <div class="card">
    
                        <!--Card image-->
                        <img class="cards-img-basic img-responsive" src="../images/pdf1.jpg" id="pdf" alt="Card image cap">
                        <!--/.Card image-->
    
                        <!--Card content-->
                        <div class="card-block">
                            <!--Title-->
                            <h4 class="card-title text-center">PDF Books</h4>
                            <!--Text-->
                            <p class="text-muted card-text">Some quick example text to build on the card title and make up
                                the bulk of the card's content.</p>
                        </div>
                        <!--/.Card content-->
    
                    </div>
                </a>
            </div>
           //More similar HTML code inbetween here....

     </div>
    </div>
</div>

Answer №1

As the div appears on the screen, I would like to transition the color smoothly instead of it changing abruptly when it reaches the top of the browser.

One way to achieve this is by using .offset().top instead of .position().top to accurately determine the distance between the object and the document's top rather than its offset parent.

By comparing the scroll distance with this value, you can identify when the object is at the top of the screen.

To make the object visible as it comes into view, calculate by subtracting the object's height from its .offset().top and compare that with the scroll position.

For example:

if($(document).scrollTop() > $('.slide2').offset().top - $('.slide2').height())

In the following code snippet, I have outlined the element with a gold border to show how this works. Additionally, I have added a CSS property for transitions to ensure smooth color changes as suggested by Lansana.

Edit: The implementation details may vary based on your document structure and CSS styles. Make sure to adjust your jQuery conditions to match the layout and styling of your elements for the desired effect. For instance, if you have conflicting conditions for different elements appearing simultaneously, some conditions may not trigger correctly, leading to issues in the functionality.

I have updated the code below to revert the background color to white when at the top of the page. I replaced references to .slide1 with hrOffset, pointing to the hr tag under .homeContainer right below "Quick Links" header. Furthermore, I modified the CSS class to set the background color to white.

$(window).on("scroll touchmove", function() {

  var homeOffset = $('.homeContainer').offset().top - $('.homeContainer').height();
  var hrOffset = $('.homeContainer').find('hr.transGrow').offset().top - $('.homeContainer').find('hr.transGrow').height();
  var slide2Offset = $('.slide2').offset().top - $('.slide2').height();
  var elms = $('body').add('header');

  if ($(document).scrollTop() >= homeOffset) {
    setTimeout(function() {
      $('.transGrow').addClass('grow');
    }, 275);
    $(elms).addClass('landing').removeClass('quickLinks');
  };
  if ($(document).scrollTop() > hrOffset) {
    $(elms).addClass('quickLinks').removeClass('landing aboutUs');
  };
  if ($(document).scrollTop() > slide2Offset) {
    $(elms).addClass('aboutUs').removeClass('quickLinks');
  };
});
.landing,
.quickLinks,
.aboutUs {
  transition: background-color 400ms;
}
.landing {
  background-color: #fff;
}
.quickLinks {
  background-color: #9575CD;
}
.aboutUs {
  background-color: #9CCC65;
}
.slide2 {
  border: 2px solid gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="homeContainer">
...
[Remaining HTML code here]
...
</div>

Answer №2

To achieve the effect you desire, apply a transition to your backgrounds and create modifier classes that alter their colors. This change in color will then smoothly occur thanks to the transition.

Take this for example:

.landing, .quickLinks, .aboutUs {
    background-color: #fff;
    -webkit-transition: background-color 1s ease;
    -moz-transition: background-color 1s ease;
    transition: background-color 1s ease;
}
.landing.loading--active {
    background-color:#F8BBD0;
}
.quickLinks.quickLinks--active {
    background-color: #9575CD;
}
.aboutUs.aboutUs--active {
    background-color: #9CCC65;
}

By adding loading--active, quickLinks--active, or aboutUs--active to their respective divs, the background colors will smoothly transition over one second using the ease timing function.

As the user scrolls, utilize jQuery to add the modifier classes like so:

$(document).on('scroll', function () {
    if (/*div.landing scrolled to*/) {
        $('.landing').addClass('landing--active');
    }

    if (/*div.quickLinks scrolled to*/) {
        $('.quickLinks').addClass('quickLinks--active');
    }

    if (/*div.aboutUs scrolled to*/) {
        $('.aboutUs').addClass('aboutUs--active');
    }
});

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

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

How to manipulate wrapping behavior in flexbox

My flex container holds three divs, arranged in two rows: First row: One div with a fixed width Another div that should stretch to fill the remaining space Second row: Just one item However, the first div stretches to 100% width and pushes the seco ...

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

What sets apart li.parent from ul?

I am facing some confusion with this parent keyword. Are li.parent and ul the same thing? If so, can someone please explain what this means? Thank you. (nav and sidebar are classes). .sidebar ul.nav .active > a:focus, .sidebar ul.nav li.parent a.active ...

Establishing a preset date in the Eonasdan Bootstrap datepicker

I implement the Calendar functionality using a library available at this link Below is the HTML code snippet: <div class="form-group" id="div_mydatecontainer"> <div class='input-group date' id='datetimepicker ...

The issue of basic authentication failing to function on Internet Explorer and Chrome, yet operating successfully on Firefox

Here is how my authentication code looks: public class BasicAuthenticationMessageHandler : DelegatingHandler { private const string BasicAuthResponseHeader = "WWW-Authenticate"; private const string BasicAuthResponseHeaderValue = "Basi ...

Populate a Dropdown Menu with Directory Content for User Selection of d3.js JSON Data

I have a d3 forced-directed graph that is currently using a static JSON file for data: d3.json("../Data/sample.json", function(error, graph) { //do stuff }); However, I would like to give the user the ability to select the data file from a drop-down ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

The argument represented by 'T' does not align with the parameter represented by 'number' and therefore cannot be assigned

I am confused as to why, in my situation, <T> is considered a number but cannot be assigned to a parameter of type number. Changing the type of n to either number or any resolves the issue. Error: Code: const dropFoo = <T>(arr: T[], n: T): T ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...

Creating beautiful prints with images

I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here ...

Modify the text in a paragraph by clicking on a link using JQuery and HTML

I'm attempting to implement a straightforward action, but I'm facing some challenges. My navigation bar consists of a few links followed by a text section. What I aim for is that when I click on a link, the paragraph of text should change to refl ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

The functionality of CSS scroll snap does not seem to be compatible with the CSS Grid

When utilizing CSS scroll snap with Flexbox, the snapping functionality works adequately: * { box-sizing: border-box; margin: 0; padding: 0; } .slider { font-family: sans-serif; scroll-snap-type: mandatory; scroll-snap-points-y: repeat(100vw ...