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

Creating dynamic JSX content in NextJS/JSX without relying on the use of dangerouslySetInnerHTML

I have a string that goes like "Foo #bar baz #fuzz". I'm looking to create a "Caption" component in NextJS where the hashtags become clickable links. Here's my current approach: import Link from "next/link"; const handleHashTag = str => st ...

angular index.html code displayed

I successfully deployed an Angular app on a server in the past without any issues. The Angular version is 6.1.1, Angular CLI version is 6.2.9, npm version is 6.13.4, and node version is 10.18.0 for both local and server environments. The server is running ...

Bizarre Drop-down Peculiarities

Having a perplexing issue where the 'search' list item is oddly shifted below the dropdown box only when it is displayed. The other list items remain in their correct positions. Any advice on how to resolve this? The appearance and functionality ...

Error in JavaScript goes undetected when utilizing asynchronous AJAX

Having recently started working with ajax and javascript, I find myself puzzled by the fact that my error is not getting caught when making an asynchronous ajax call. I did some research on a similar issue in this query (Catch statement does not catch thr ...

The ion-datetime in Ionic 4 ensures that the floating label always remains visible, even when the input

When an ion-datetime field in Ionic 4 has no value, the label always floats as shown below. Here is my code snippet: <form [formGroup]="statusHandlerForm"> <ion-item class="input-container " align-items-center no-padding> <ion-la ...

Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is http://mywebsite.com/[category that doesn't exist]. Despite the code snippet provided below, I am unable to reach the catch block in asyncData. async asyncData({ params, store }) { try { await store.dispatch(&ap ...

Using PHP to validate a read-only textbox

I am trying to implement validation on a Datepicker that is set to readonly, but I am facing issues with my current code. Can someone please assist me? Below is the JavaScript code used for error trapping: <script type="text/javascript"> $(func ...

Modify element classes with a single button using jQuery

Is there a way to apply or remove a class from another div using jQuery? Take a look at my code snippet below. Appreciate any help! $(".btns").on("click", function() { $(".box").addClass("addClass") }) .box{ background: yellow; } .box.addClass{ ba ...

Guidelines for redirecting an on-click action to navigate to a link rather than entering text

Using the AJAX Live Search PDO feature, I made a modification to have the displayed words link to their respective URLs. However, clicking on the table does not redirect to the link but instead inputs the text. I am looking for a way to make the entire row ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Tips for adding jQuery UI styling to elements generated dynamically

I have a challenge with generating text fields using jquery while applying jquery ui styling to the form. The issue is that the dynamically created elements do not inherit the css styles from jquery ui: let index = 0; $('#btn_generate').on(& ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

What is the best way to display Bootstrap dynamic tabs in a single row without them overflowing and requiring a scroll button to access all the tabs

Is there a way to dynamically display Bootstrap tabs? I want the content in the tab to show when the link is clicked, and also have a close button. I need the tabs to be aligned in a single row without wrapping down if they don't fit. Here's an ...

Issue with pop up window causing button click event to malfunction

I am facing an issue where the button click event works fine outside of a pop-up window but does not fire when inside the pop-up window. In my HTML code, the part that calls the button event outside of the pop-up window works perfectly, but inside the pop- ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

No response being received from Ajax request

Having some trouble with an ajax function I developed for a small project. The issue lies in running the code inside the .done() function. This function is supposed to receive a json object from php (which I am obtaining a response via cURL), but it appear ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

When properties are passed and then mapped, they become undefined

While I experience no errors when directly mapping the array, passing the same array through props results in an error stating "Cannot read property 'map' of undefined." Brands Array const brands = [ { key: 1, Name: "Nike", }, { ...

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...