Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/

I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its original color when at the top of the div. I noticed that adding height instead of background color works fine, but I can't figure out why the background color isn't changing as expected:

$(function(){
var content = $(".content");

$(".box").scroll(function(event){
var positionofscroll = $(".content").scrollTop();

if(positionofscroll == 0){
content.stop().animate({
backgroundColor:"rgba(105, 63, 63, 0.69)"
},500);
}else {
content.stop().animate({
  backgroundColor:"red"
},500);

}
}); //scroll


});
.box{
  width:100%;
  height:500px;
  background:gray;
  overflow:auto;
}

.content{
  color:white;
  display:flex;
  justify-content:center;
  align-items:center;
  height:1000px;
  background:red;
  font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<!--Shadow Box when user scrolls -->

<div class="box">
  <div class="content">
    I'm content
  </div>
  
</div>

Answer №1

Consider incorporating jQuery UI for smoother animations, as .animate() may not animate colors without adjustments or a color plugin; refer to .animate() for more information.

Understanding Animation Properties and Values

It is important to note that all properties being animated should transition to a single numeric value, with exceptions mentioned below. Most non-numeric properties cannot be smoothly animated using basic jQuery features (For instance, animating width, height, or left is feasible, but animating background-color requires the use of the jQuery.Color plugin).

Additionally, adjust the selector at positionofscroll to utilize $(this).scrollTop(); also change the comparison operator to > within the if statement.

$(function() {
  var content = $(".content");

  $(".box").scroll(function(event) {
    var positionofscroll = $(this).scrollTop();
    console.log(positionofscroll);
    if (positionofscroll > 0) {
      content.stop().animate({
        backgroundColor: "rgba(105, 63, 63, 0.69)"
      }, 500);
    } else {
      content.stop().animate({
        backgroundColor: "red"
      }, 500);

    }
  }); //scroll


});
.box {
  width: 100%;
  height: 500px;
  background: gray;
  overflow: auto;
}
.content {
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 1000px;
  background: red;
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>
<!--Shadow Box when user scrolls -->

<div class="box">
  <div class="content">
    I'm content
  </div>

</div>

Answer №2

Give this a shot:

let content = $(".content");

$(".box").scroll(function(event)
{
  let scrollPosition = $(this).scrollTop();
  if (scrollPosition > 0)
  {
    $(".content").css('background-color','rgba(105, 63, 63, 0.69)');
  }
  else 
  {
    $(".content").attr('style','');
  }
}); 

Fiddle: https://jsfiddle.net/7d3eq92m/

If you wish to add animation to the background color change, include the following CSS to .content:

transition: all 0.3s ease-out; 

or something similar. I hope this information is helpful!

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

Enhancing User Experience in VueJS with Pug Templates and Transitions

Managing multiple 'pages' of content within a multi-step process can be challenging, especially when trying to incorporate VueJS's transition feature for a carousel-like slide in/out effect. The contents being transitioned are stored in sepa ...

Checking for identical inputs in a React component's onChange event: how can it be done?

I'm currently working on implementing an onChange event in React to validate if two input fields are identical, specifically for confirming a password. The goal is to display a message below the input fields as users type, indicating whether the passw ...

Designing architecture for NPM packages in TypeScript

I am currently developing multiple NPM packages using TypeScript and I am exploring the most effective strategies for supporting various target architectures. When compiling to ES3, there is extensive support but it comes with additional boilerplate for c ...

The file browser fails to open following an AJAX request in the Firefox browser

I am encountering an issue where the programmatic click on a file input does not open the file browser in Firefox after a successful AJAX call, although it works perfectly in Chrome. The problem persists on version 82.0.3 (64-bit) of Mozilla Firefox for Ub ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Struggling to perfectly center the NavBar within the wrap container

After working on my navbar and utilizing this site for guidance, I was able to center it using text align. However, there is an odd indent in the navbar that I can't seem to figure out. This indentation throws off the alignment when centered, giving i ...

Clicking multiple times will impede the progress of AJAX requests

My webpage has multiple buttons that can be clicked very quickly, but it seems like Chrome is struggling to keep up with the speed? $(document).ready(function() { $('.favorite-button').unbind('click').click(function() { addLine ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Fetching the URL for the Facebook profile picture

Utilizing satellizer for authentication in a MEAN application. Once the authentication process is complete, I aim to retrieve the user's profile picture. Below is the code snippet that I am using: Angular Controller (function(){ 'use strict ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

What is the process for selecting the Node version when installing with .nvm?

I am having an issue with nvm in the terminal. When I try to run npm install <something>, it always installs the package in node version 9.4.0, regardless of the version set using nvm. Even after switching to node version 10.15.3 using nvm use v10.1 ...

Enhance scrolling with a bounce effect

My goal is to implement a smooth scrolling experience with a bounce effect when the user over-scrolls, meaning they scroll too much to the top or bottom. I found an answer on Stack Overflow that explains how to achieve smooth scrolling, but I also want to ...

Issue with loading Three.js asynchronously

My attempt to determine the maximum value of a point cloud data using the following code proved unsuccessful. import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader"; let max_x = -Infinity; function initModel() { new PLYLoader().load ...

Alignment of a div at the bottom inside a jumbotron using Bootstrap 4

Searching for answers on how to vertically align a div within a jumbotron, I have come across plenty of solutions for middle alignment but none for bottom alignment. <section id="profileHero"> <div class="container"> <d ...

Internet Explorer experiencing difficulties displaying elements

On occasion, my website (find-minecraft-servers.com) may appear distorted in Internet Explorer. Sometimes, the number under Servers Listed in the green-ish banner fails to display correctly, despite being present in the source code. This issue seems to be ...

There seems to be a malfunction with the hide and reset features, as they are

I have encountered an issue while working on hiding a series in Google Charts when clicked on the legend. The problem arises when an extra column is added to display tooltips on the bars, causing the functionality to break. Please check out the demos below ...

Comparison of Transform plugin and Syntax plugin within Babel

I am interested in incorporating Class properties into my webpack configuration. While following a tutorial on the website (www.survivejs.com), I came across two plugins being added to the .babelrc file: babel-plugin-syntax-class-properties and babel-plugi ...

Troubleshooting VueJS's Dilemma with Quotation Marks

When I try to parse a string containing either double quotes or single quotes, an error is being thrown: JSON Unexpected token. Is there a way to properly parse and bind it to a variable in Vue.js? PHP $arr = array(); $arr[0]['description'] = ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...