A step-by-step guide on how to implement a window scroll-controlled color transition

I've implemented jQuery code to change the opacity of my navbar's background as the user scrolls, transitioning from transparent to blue. Here's the snippet:

 $(window).scroll(function(){

  var range = $(this).scrollTop();
  var limit = 450;

  var calc = range / limit;
  console.log(range);

  //Bg Opacity Control
  if (range === 0) {
    $('.navBg').css({
      opacity: 0
    });

  }else if(range < limit){
    $('.navBg').css({
      opacity: calc
    });

  }else if(range > limit){
    $('.navBg').css({
      opacity: 1
    });
  }

});

Now, I want to add a font color transition that mirrors the background change based on scroll position. I've set up arrays with hexadecimal values for color scales:

 
  var fontScale = ["#19BFFF", ... "#FFF"];
  
  var hoverScale = ["#eaeaea", ... "#323031"];

How should I implement the font color transition using these arrays? Should I use loops or conditional statements?

Here are the jQuery selectors for elements that will change color:

    
    //Main Font color using fontScale array
    $('.navbar .navbar-header .navbar-brand')
    $('.navbar #navbar ul li a')

    //Active links using hoverScale array
    $('.navbar #navbar .navbar-nav > .active > a')
    //Hover links using hoverScale array
    $('.navbar #navbar ul li a:hover')

Any advice on how to proceed would be appreciated!

**UPDATE

Here is the HTML structure:

  
  <div class="navBg">
    </div>
    <nav class="navbar navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <span class="navbar-brand" href="#home">JG</span>
        </div>
        <div id="navbar" class="navbar-collapse collapse navbar-right">
          <ul class="nav navbar-nav">
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#services">Services</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
    </nav>

This is the updated jQuery code:

  
  var currentFontIndex = range * fontScale.length / limit;

  currentFontIndex = Math.round(currentFontIndex);
  console.log(fontScale[currentFontIndex]);

  if(currentFontIndex > fontScale.length){

    $('.navbar .navbar-header .navbar-brand').css({
      color: fontScale[currentFontIndex]
    });
    $('.navbar #navbar ul li a').css({
      color: fontScale[currentFontIndex]
    });

  }

However, the styles aren't being applied despite correct index values in the fontScale array. Any thoughts on why this might be happening?

Looking forward to your input!

Answer №1

If you can translate a Y coordinate (ranging from 0px to 450px) into opacity values (ranging from 0 to 1), then you have the ability to do the same for array indices!

0px -> 0 opacity -> index 0
450px -> 1 opacity -> index 10 

...

currentScrollTop-> currentColorIndex 

Utilize the cross product method!

currentColorIndex = currentScrollTop * 10 / 450

or

var range = $(this).scrollTop();
var limit = 450;

var fontScale=[
 ....
]

var currentFontIndex = range * fontScale.length / limit;

 //Naturally, an integer alone won't suffice for the index,
 //thus, you need to incorporate a rounding function, such as: 
currentFontIndex = Math.round(currentFontIndex);

if(currentFontIndex > fontScale.length)
     currentFontIndex = fontScale.length

$('.navBg').css('color', fontScale[currentFontIndex]);

Answer №2

As the user scrolls down by 45px each time, I aim to dynamically change the font color using a sequence of colors stored in arrays.

To determine which color to apply from the array, you can divide $(this).scrollTop() by 45.

var fontScale = [
  "#19BFFF",
  "#336CFF",
  "#4CCDFF",
  "#66D4FF",
  "#7FDBFF",
  "#99E2FF",
  "#B2E9FF",
  "#CCF0FF",
  "#E5F7FF",
  "#FFF"
];

var div = $("div");

$(window).on("scroll", function(e) {
  var curr = Math.round($(this).scrollTop() / 45);
  console.log(curr);
  div.css("color", fontScale[curr])
}).scroll()
body {
  height: 500px;
  background: yellow;
  position: absolute;
  display: block;
  text-align: center;
  top: 50vh;
  left: 35vw;
  font-size: 36px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div>abc</div>
</body>

Answer №3

Illustrating the concept with a simple example using for ( ; ; )

var fontScale = ["#19BFFF",
  "#336CFF",
  "#4CCDFF",
  "#66D4FF",
  "#7FDBFF",
  "#99E2FF",
  "#B2E9FF",
  "#CCF0FF",
  "#E5F7FF",
  "#FFF"
];
var height = $(window).scrollTop();
$(window).scroll(function() {


  for (var i = 0; i < 3; i++) {
    if (height >= 0) {
      $('body').css('color', fontScale[i]);
    }
  }
  for (var i = 3; i < 6; i++) {
    if (height > 100) {
      $('body').css('color', fontScale[i]);
    }
  }
  for (var i = 6; i < fontScale.length; i++) {
    if (height > 200) {
      $('body').css('color', fontScale[i]);
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
lorem ipsum lorem ipsum lore lorem ipsum lorem ipsum lorem<br>
ipsumlore 

Utilizing conditional intervals to assign colors dynamically

Answer №4

Here is a solution that has been proven to be effective:

var index = range * fontScale.length / limit;

  index = Math.round(index);
  console.log(fontScale[index]);

  if(index <= fontScale.length){

    $('.navbar .navbar-header .navbar-brand').css(
      'color', fontScale[index]
    );
    $('.navbar #navbar ul li a').css(
      'color', fontScale[index]
    );

  }

Now the only remaining challenge is locating a tool that supports the creation of personalized color palettes. I am in need of colors ranging from #00ADEF (a light blue) to #FFF (white). The existing colors in my arrays are not suitable and are creating an unattractive appearance. Can someone suggest a reliable resource for this purpose?

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

Adjusting the height of the navbar items to align with the size of the

In the bootstrap navbar below, I am trying to enlarge the search field to be large using 'input-lg', but this causes the other items in the navbar not to vertically center correctly. How can I align the other items in the navbar with the large in ...

Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs Below is my db file setup: import admin from "firebase-admin"; import serviceAccount from "./serviceAccountKey.json"; if (!admin.apps.len ...

Flexbox: Arrange header and footer in a sidebar layout using flexbox styling

In my content layout, I have structured the sections as header, content, and footer. While I want to maintain this order for small devices, I am looking to shift the header and footer to the sidebar on desktop. I have already implemented this using floats ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

Google Fonts are displaying in a bold style even when the bold property is not set

I need assistance with an issue involving emails going from Salesforce to Outlook 365. Here is the HTML code snippet: <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css"> <style> body ...

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

What could be causing the unexpected gap between the first two elements and the third in my flexbox layout?

I am facing an issue with the layout of my third child element. Instead of appearing below the first two children, it is wrapping around to the bottom of the container. Can anyone explain why this is happening and suggest a solution? Even though I have se ...

What is the process for generating a GET request for selected checkboxes and subsequently showcasing the data on an HTML webpage?

Currently working on an app project and need assistance with implementing a feature. I have successfully set up a POST method for the checkboxes that are checked, but I am unsure how to retrieve this data and display it on my HTML page using a GET method ...

The HTML navbar seems to have a mind of its own, disappearing and shifting around unpredictably as I zoom in or resize

WHEN DISPLAYING THIS CODE, IT IS ADVISED TO VIEW IN FULL PAGE MODE This code includes navigation, header, and styling elements. However, when the browser is zoomed in or out, the navbar tends to move around and eventually disappears off the screen if wind ...

Developing 'Drop Down' Views in AngularJS

With AngularJS, I have successfully rendered a table containing a list of items with unique IDs for each row. Now, my goal is to create a pull-down view that allows users to see detailed information about each row. This pull-down view will include a nested ...

How can I place a div using pixel positioning while still allowing it to occupy space as if it were absolutely positioned?

I successfully created an slds path element with multiple steps. I want to display additional subtext information below each current step, but there might not always be subtext for every step. To achieve this, I created an absolute positioned div containi ...

Exploring JSON data hierarchies with AngularJS using ng-options

In my web app, I am utilizing AngularJS to create two dropdown lists using ng-options. The first dropdown displays a list of countries The second dropdown provides language preferences for the selected country As I am still new to AngularJS, I am able t ...

Tips for Choosing a Tab in angular-ui: AngularJS

Is there a way to select the last tab without using ng-repeat? I want to avoid using ng-repeat but still need to select tabs. Any suggestions? If you'd like to see the code in action, you can visit: http://plnkr.co/edit/ZJNaAVDBrbr1JjooVMFj?p=preview ...

Guide to selecting and clicking multiple elements with a specific class using jQuery

On my html page, I have the following elements: $(".pv-profile-section__card-action-bar").length 3 I want to click on all of these elements instead of just the first one. Currently, I am achieving this with the code: $(".pv-profile-section__card-action- ...

While in the process of developing a React application, I have encountered the following challenge

PS F:\Programming Tutorials Videos\R Practice> npx create-react-app custom-hook npm ERR! code ENOTFOUND npm ERR! syscall getaddrinfo npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.npmjs.org/create-react-app failed, reaso ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Ways to simultaneously apply fade in and fade out effects using CSS

body { background-image: url("background.jpg"); background-attachment: fixed; font-family: 'Roboto', sans-serif; color: #333333; } #container { height: 1000px; } /* HEADER WITH NAVIGATION BAR AND LOGIN OPTION */ #head { position: abso ...

I'm curious about how to use JQuery to pinpoint the firstName within a JSON String and retrieve its corresponding ID

Does anyone have an idea about the outcome in the alert? Is it a regular string, an object, or JSON? How can I select one of the entities and find another based on that selection? For example, I want to choose the first name and retrieve the ID from it. It ...

Remove a row from a Jquery Jtable

I am running into difficulties when trying to delete rows, and I suspect that the issue might be related to the post[id] not being properly sent. Although the delete message appears, the row is not actually deleted. Below is the snippet of my code: JAVASC ...