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

What is the best way to dynamically fill an HTML select box with data using jQuery in the C# code-behind?

Trying to populate a dropdown on an HTML front end and C# code behind from a blank ASPX page acting as a local server, using jQuery/AJAX. As a newcomer to this, any assistance is greatly appreciated. After attempting various methods without success, here ...

Angular animations are failing to function in the Visual Studio 2017 template

I am facing a challenge with incorporating animations in Angular 2 using Visual Studio 2017. I believe there must be a simple solution that I am overlooking at the moment. My goal is to animate certain elements and I have been testing the animations by tri ...

Encountering Difficulty Fetching Data from JSON File Utilizing AngularJS

insert image description hereI am struggling to fetch data from a Json file using Angular Js. I am attempting to retrieve the Json data from a URL by clicking a button in Angular Js, and also add an empty tr td in a table when the button is clicked. ...

A step-by-step guide on retrieving information from a span and em element with Beautiful Soup

Currently, I am developing a code that is responsible for extracting data from various web pages. # Here's the content of task.py import requests from bs4 import BeautifulSoup url = ('https://www.naukri.com/job-listings-Python-Developer-Cloud-A ...

Issue with jQuery select box (roblaplaca) and its custom scroll bar functionality not functioning as expected

Recently, I implemented the custom select box script from . This script allows for two select boxes, where the second one updates dynamically using AJAX when there is a change in the first select box. Below is a sample of the HTML code: <option>One& ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

Accessing a Dropdown List through PHP in an HTML Document

I am currently working on a PHP file that is responsible for parsing a JSON list and then feeding it to a combobox: <?php $jsonData = '{"marco":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25484457464a6551405651 ...

The arrival of chat featuring Ajax, long-polling, and support for multiple users has finally

Imagine a site with three modules: "links", "home", and "chat". The "links" and "home" modules are static pages that do not require long polling. However, in the "chat" module, new messages may arrive at any time from other users, requiring an immediate up ...

Utilizing async parallel for executing multiple queries

Hey there, I'm new to Javascript and I've been trying to work with the async.parallel function. I have a specific task where I am fetching data from my database and storing it in an array called "reviewArr." Then, I want to return this array of ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

Displaying a List of Files Uploaded with Jquery File Upload in an ASP.NET MVC Application

I have successfully installed the NuGet Jquery File Upload Plugin. The uploader functions flawlessly, allowing me to easily drag and drop files for upload to my server. However, there are two issues that are hindering the completion of this project: Aft ...

Getting the Firebase Project Name or ID from a Cloud Function is a simple task that involves using

While working with Cloud Functions, I need to retrieve the project name from one of my Javascript server files. The project name is stored in .firebaserc file, but I am not sure if this file is accessible on the server side. Is there a way to achieve somet ...

Searching for a way to detect when a user clicks the back button on their Android or iPhone device using JavaScript or

In the process of building a Single Page Application (HTML5) utilizing the following plugins: - Sammy.js - Knockout.js - Require.js - Jquery.js This app is designed for Android, iPhone, and Windows mobile devices. Many scenarios revolve around cli ...

A guide to update values in mongodb using node.js

I'm working on tracking the number of visitors to a website. To do this, I've set up a collection in my database using Mongoose with a default count value of 0. const mongoose = require('mongoose'); const Schema = mongoose. ...

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...

Transforming this JavaScript code to be less intrusive by implementing an event listener for an unidentified ID

As I work on enhancing the functionality of this user interface, I've encountered a challenge with two tabs that require a proper event listener to ensure my JavaScript functions smoothly. This obstacle has been hindering my progress, but as I delve i ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...