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

Interactive text that changes when hovered over in an HTML document

My table contains text and I have implemented code that displays a small text when hovering over it. I would like the entire column to trigger the text display on hover, ideally in a larger size. Any suggestions on how to achieve this? ...

To add additional nested data to a JSON object in JavaScript, you can use the push method or update

Looking to enhance the nested object data within my existing object The current structure of the JSON object array resembles this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ ...

How can Chinese characters be transformed into XML/HTML-style numerical entities and converted into Unicode UTF-8 encoding?

I have a situation where I need to change a text that contains both English words and Chinese characters into a format that includes XML/HTML-style numerical entities for the Chinese characters. Here's an example of the original text: Title: 目录. ...

The method piSession.buildPageInteractionSession is not valid

Hey there! I am facing an issue with a simple AJAX call to a PHP file. The request should be sent to the server and return back in an HTML input field. Unfortunately, I have not been able to resolve this error so far. Below is the code snippet: HTML: ...

Utilize jQuery to transform array values into date objects

I am receiving an array from a .net controller. The values I am getting for dates are: /Date(1445256000000)/ and /Date(1445256900000)/ Instead of this, I need to convert these into proper date values. Now that I have an array of objects, I want to upda ...

Can you please provide me with information on how I can send messages to US numbers using a toll-free number?

I attempted to utilize this code in the SNS console, but it showed a failure. I am seeking guidance on how to send a message using a TFN number. async sendMessage(testId: number) { const mobileNo = test.customer.phoneNo; const params = { Message: ...

What's the best way to place the text or operator from a button into an input field?

Hello, I am currently working on developing a calculator. However, I have encountered an issue where clicking on operator buttons such as +, -, /, *, and the dot button does not add them to my input field. Additionally, when these buttons are clicked, the ...

Retrieve data from a different div, perform a subtraction operation, and dynamically update yet another div using jQuery

Looking to extract a specific div class value, subtract 500 from it, and display the result in another div. Unclear about the steps needed to show the subtraction outcome on the other div. Consider this scenario: <div class="main-value">6000</d ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

Tips for saving and accessing the value of an md-select ng-model in an AngularJS dialog?

Currently, I am utilizing a template to populate an md-dialog box: The procedure for displaying the dialog: $scope.showDialog = function(element) { var parentEl = angular.element(document.body); $mdDialog.show({ template: element, scope: $scope, pr ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

How to troubleshoot Props not functioning in nextjs-typescript?

I'm having trouble with props in my project and I can't seem to figure it out! Here are the three files. I'm still learning typescript but everything seems fine in the code, yet it's not working! Here is index.tsx file: const Home: ...

Validation can only be performed one tab at a time

I have utilized BootstrapWizard to create a wizard, but I am in need of validating the input before proceeding to save them. Currently, when I complete the first tab, I am unable to move on to the next tab because the valid() method returns false. The val ...

What is the best method to restrict the size of a div to match the dimensions of the

In my webpage, I have a menubar (div) that contains bookmarks. However, when too many bookmarks are added, the menu becomes too wide for the page size I prefer (1280, 720) and becomes scrollable, causing some bookmarks to be out of view. My goal is to ens ...

"Enhance your form experience with MagicSuggest by automatically moving to the next

When using Magic Suggest, I encountered an issue with the onBlur function. Instead of moving focus to the next normal textbox as intended, it automatically moves to the next magicsuggest element if no onBlur function is set. However, when an onBlur functio ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

Injecting Javascript before page code in Chrome Extension Content Script allows for manipulation of webpage elements

I am currently working on developing a Chrome extension that involves injecting a script into a webpage before any other scripts present. This is crucial for my project as I am utilizing the xhook library to intercept XHR requests, which necessitates overw ...