Changing background color on scroll using jQuery

Looking to create a cool effect where the background color of a fixed header changes as the user scrolls down a full-page block website. Managed to get it mostly working in this Pen, but struggling with determining how much has been scrolled to trigger the change.

A bit more detail: Need the switch to happen at 400px of scroll. The different background colors are stored in an array for easy fetching. Here's my jQuery code snippet:

$(document).ready(function(){
  var bgArray = ["#252525","#333333","#454545","#777777"];  
  var scrollHeight = 400;
  var scrolled = $(window).scrollTop(); // What does this exactly measure?

  $(window).scroll(function() { // Can these conditions be combined into one?
    if(scrolled < scrollHeight) {
      $('header').css('background', bgArray[0]);
    }
    if(scrolled > scrollHeight) { // i.e more than 400px
      $('header').css('background', bgArray[1]);
    }
    // and so on (800, 1200...)
  })
})

Check out the Pen for the complete code. Any ideas or suggestions would be really helpful!

Answer №1

Newly Updated Technique (2019)

In order to dynamically change the background of the header based on the visible block below it while scrolling, follow these steps:

  • Since the header has a fixed position, you can calculate the window scroll amount using $header.offset().top,

  • The index of the current block in view is determined by dividing the scroll amount by the height of each block,

  • To adjust for the header's height, use the formula:

    Math.floor(($header.offset().top + headerHeight) / sectionHeight)
    .

Take a look at the simplified demonstration provided below:

$(function() {
  var $header = $('header'),
    $window = $(window),
    bgArray = ["#252525", "red", "blue", "green"],
    headerHeight = 50,
    sectionHeight = 400;

  $window.scroll(function() {
    $header.css('background', bgArray[Math.floor(($header.offset().top + headerHeight)
        / sectionHeight)]);
  });
});
:root {
  --header: 50px; /* header height */
  --block: 400px; /* block height */
}

* {
  box-sizing: border-box; /* include padding in width / height calculations */
}

... (CSS code continues here)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
... (HTML elements continue here) ... 


Original Approach

The initial solution involves determining the visibility of each block relative to the window scroll using jQuery functions. By comparing offsets and heights, the script changes the header color when entering different blocks - refer to the demo:

$(document).ready(function() {
  var $header = $('header'),
    $window = $(window),
    bgArray = ["#252525", "#333333", "#454545", "#777777"],
    headerHeight = $header.outerHeight();

  $window.scroll(function() {
    for (var i = 1; i < 5; i++) {
      if ($window.scrollTop() + headerHeight > $('.block-' + i).offset().top) {
        $header.css('background', bgArray[i - 1]);
      }
    }
  });
});
@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,700');
body {
  font-family: 'Roboto', sans-serif;
  ... (CSS styling continues) ...
}

... (CSS styling continues) ...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
... (HTML elements continue here) ... 

It's worth noting that this method iterates through sections unnecessarily during every scroll update, leading to potential performance concerns.

Answer №2

Instead of using scrolled as a fixed variable, consider incorporating it directly into your condition

By doing this, you will create a dynamic effect for all elements within the wrap div

$(document).ready(function(){
var bgArray = ["#252525","#333333","#454545","#777777"];
$(window).scroll(function() { 
    for(var i = 1; i < bgArray.length; i++) {
      if ($(window).scrollTop() > $('.wrap div:nth-child(' + i + ')').offset().top) {
        $('header').css('background', bgArray[i-1]);        
      }
    }
  });
})

Answer №3

Give this a try:

$(document).ready(function(){
  var backgroundColors = ["#252525","#333333","#454545","#777777"];  
  var scrollHeight = 400;

  $(window).scroll(function() {

    var scrolledValue = $(window).scrollTop(); 

    var colorIndex = Number((scrolledValue/scrollHeight).toFixed());

    if(backgroundColors[colorIndex]!=undefined)
        $('header').css('background', backgroundColors[colorIndex]);

  });
})

This code is for adjusting the background color based on scrolling position, make sure to place it inside: $(window).scrollTop()

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

Alignment of Table with Form Section

I need help figuring out how to align a table next to a form section. Here is the layout I am aiming for: #Form Label: |TextBox| Label: |TextBox| Label: |TextBox| Label: |TextBox| ---------------------------------------------- ...

Troubleshooting: Why Laravel 5 VueJS Integration is Failing

I have recently set up a Laravel project and am attempting to integrate Vue.js into it. After running the following commands in my terminal: npm install npm run dev The commands executed without any errors. However, when I tried to import the default Vue ...

Issues with javascript functionality in Internet Explorer version 9 and higher

Currently, there is a flash music player (audioplay) embedded on a website. Despite personal preferences against having music on websites, it was requested by the client. The functionality in question involves using JavaScript to trigger "stop" and "play," ...

Execute the function when the control becomes visible

Currently, I possess an input control: <input id="someID" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData"> I have a requirement to set the initial value of vm.SomeData upon user scrolling down to this control. As a begi ...

django problem with bootstrap modal

I'm having trouble with the Bootstrap 4 modal in my Django project. When I click the button, the fade effect covers the entire screen, but the modal doesn't appear. I'm currently using Django 1.9. Does anyone have any suggestions on what mi ...

Discover the way to create an HTML button with a mesmerizing transparent effect

For my website creation using Dreamweaver, I came up with the idea of utilizing Photoshop to design backgrounds. The reasoning behind this choice was that if I needed to modify button names at any point, I could simply edit the code and make the necessary ...

Getting URL parameters in VueJS after a page redirect has occurred

Currently, I am implementing a Login with Facebook feature in my VueJS application using a Third Party Service (AWS Cognito). The process involves clicking on a "Login with Facebook" button which triggers a redirect to the third party URL where a Sign Up ...

Ways to deactivate antd css-dev-only styles

I am currently working on a nextjs project using tailwind and antd. I am facing an issue where the antd Layout component styling is being applied and I am unable to remove it. :where(.css-dev-only-do-not-override-12upa3x).ant-layout-header This styling is ...

Removing Component Items in a Vue.js v-for Loop

I recently created a Vue radio button component and I'm having trouble figuring out how to delete the selected values. While my current solution deletes the actual values, the selection still remains visible. Below is the code for the component: < ...

Steps to installing npm on Ubuntu without root access:1. First, download

I have successfully installed node in a custom directory within my home folder called "local" following the instructions provided here: https://gist.github.com/isaacs/579814 Here is the output: Creating ./icu_config.gypi * Utilizing ICU in deps/icu-sma ...

Struggling with resizing a webcam feed to fit the dimensions of the iframe container?

I'm facing a challenge embedding a camera feed into a webpage that needs to display manual focus and servo controls. The issue lies in the content scaling within the iframe. Even though the iframe boundary resizes according to the window's width ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Transform Angular Material Table selection color with selection

Is it possible to customize the color of the selector in an Angular Material table when using selection? Learn more about it https://i.sstatic.net/5ZJQT.png ...

What is the most efficient way to organize a dynamic array with jQuery?

In my jQuery code, I have created two empty arrays and used AJAX to assign values to them. The issue is that the values assigned by AJAX are random, so I need to display them in an efficient way. Here's the code snippet I'm using: Code:- <se ...

How can I ensure that my style.scss file effectively interacts with my stylesheet by including imports for "variables", "globals", and "header"?

Currently, I am in the process of learning how to utilize Sass and JavaScript through VS Code. Within my project structure, I have an "app" folder where my js folder resides containing script.js, as well as a scss folder holding _globals.scss, _header.scss ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Incorporate a background image into input fields with Autofill on mobile browsers to override the default yellow background that obscures them

It is common knowledge that modern browsers apply a less than appealing yellow background to text fields when Autofill is used by visitors. A helpful workaround is known to override the default text and background colors, and even incorporate a background ...

What is the best way to showcase a category on the thumbnail of a WordPress post?

Hey everyone, I hope you're all having a great day! I need some assistance with a slider I'm creating on my WordPress site. I can't seem to figure out how to display the category of each post that appears in the slider and have it stand out. ...

Strategies for reducing the amount of space between cards in Bootstrap 4

After creating 4 cards using Bootstrap version 4.5, I noticed that the spacing is not right. I'm struggling to reduce the spacing between the cards. Have a look at the image below if you're still confused: https://i.sstatic.net/RrJLL.jpg .car ...

Having trouble finding a hyperlink with CSS selectors

I am attempting to utilize Selenium to retrieve some data from Google, but the CssSelector I have implemented is consistently returning "No element found". Below is my code snippet: //Open google page IWebDriver driver = new FirefoxDriver(); WebDriverWai ...