The color of a div tag generated by jQuery is always changing and never remains constant

I am trying to assign a random background color to each div with a class of "random-color". The code snippet that generates the random color using jQuery is functioning correctly, but there is an issue where the color disappears after 2 seconds. Here's the code snippet I have used: You can find the script from this post Random Div Color. Please help me fix this problem.

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
$(document).ready(function() {
    $(".random-color").each(function() {
        $(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
    });
});

window.sr = new scrollReveal();
div {
  height: 40px;
  padding: 10px;
  text-align: center;
  margin-bottom: 10px;
}
#d1 {
  background-color: #00A388;
}
#d2 {
  background-color: #FFFF9D;
}
#d3 {
  background-color: #BEEB9F;
}
#d4 {
  background-color: #79BD8F;
}
<script src="http://scrollrevealjs.org/js/scrollReveal.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>

  <p data-sr>Scroll Reveal-Default</p>


  <!--Enter Properties The enter keyword controls the vector origin (direction) of your animation.-->
  <!-- Reveal with a downward motion -->
  <div class="random-color" data-sr='enter top'>enter top</div>
  <br>

  <!-- The other accepted values... -->
  <div class="random-color" data-sr='enter left'>enter lef</div>
  <br>
  <div class="random-color" data-sr='enter right'>enter right</div>
  <br>
  <div class="random-color" data-sr='enter bottom'>enter bottom</div>
  <br>
  <!--Enter Properties Ends-->

  <!--Move Properties The move keyword controls the distance (in pixels) traveled during animation.-->
  <div class="random-color" data-sr='move 24px'>move 24px</div>
  <!--Enter Properties Ends-->
  Over The over keyword sets the duration (in seconds) of your animation.

  <div class="random-color" data-sr='over 0.6s'>over 0.6s</div>
  <div class="random-color" data-sr='over 1.3s'>over 1.3s</div>
  Flip The flip keyword is a rotation keyword, controlling rotation along the X axis (pitch).

  <div class="d1" data-sr="enter left, hustle 20px">enter left, hustle 20px</div>
  <div class="d2" data-sr="wait 2.5s, ease-in-out 100px">wait 2.5s, ease-in-out 100px</div>
  <div class="d3" data-sr="move 16px scale up 20%, over 2s">move 16px scale up 20%, over 2s</div>
  <div class="d4" data-sr="enter bottom, roll 45deg, over 2s">enter bottom, roll 45deg, over 2s</div>


</body>

</html>

Answer №1

The issue with your code is that the library ScrollReveal is overriding your CSS styles. By cleaning up your code and removing the library, you can get your code to work properly without any issues related to the jQuery code used to assign random background colors to elements on your page.

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
$(document).ready(function() {
    $(".random-color").each(function() {
        $(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
    });
});
div {
  height: 40px;
  padding: 10px;
  text-align: center;
  margin-bottom: 10px;
}
#d1 {
  background-color: #00A388;
}
#d2 {
  background-color: #FFFF9D;
}
#d3 {
  background-color: #BEEB9F;
}
#d4 {
  background-color: #79BD8F;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>

  <p data-sr>Scroll Reveal-Default</p>


  <!--Enter Properties The enter keyword controls the vector origin (direction) of your animation.-->
  <!-- Reveal with a downward motion -->
  <div class="random-color" data-sr='enter top'>enter top</div>
  <br>

  <!-- The other accepted values... -->
  <div class="random-color" data-sr='enter left'>enter lef</div>
  <br>
  <div class="random-color" data-sr='enter right'>enter right</div>
  <br>
  <div class="random-color" data-sr='enter bottom'>enter bottom</div>
  <br>
  <!--Enter Properties Ends-->

  <!--Move Properties The move keyword controls the distance (in pixels) traveled during animation.-->
  <div class="random-color" data-sr='move 24px'>move 24px</div>
  <!--Enter Properties Ends-->
  Over The over keyword sets the duration (in seconds) of your animation.

  <div class="random-color" data-sr='over 0.6s'>over 0.6s</div>
  <div class="random-color" data-sr='over 1.3s'>over 1.3s</div>
  Flip The flip keyword is a rotation keyword, controlling rotation along the X axis (pitch).

  <div class="d1" data-sr="enter left, hustle 20px">enter left, hustle 20px</div>
  <div class="d2" data-sr="wait 2.5s, ease-in-out 100px">wait 2.5s, ease-in-out 100px</div>
  <div class="d3" data-sr="move 16px scale up 20%, over 2s">move 16px scale up 20%, over 2s</div>
  <div class="d4" data-sr="enter bottom, roll 45deg, over 2s">enter bottom, roll 45deg, over 2s</div>


</body>

</html>

If you refer to the documentation for the library, you will find that there is an event triggered when an animation completes. You can utilize this event to apply your own CSS styles after the animation finishes, preventing it from being overridden by the library.

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];
$(document).ready(function() {
   
  
window.sr = new scrollReveal({
  complete:function(el){
        var $this = $(el);
        if($this.hasClass('random-color')){
          $this.css('background-color', colors[Math.floor(Math.random() * colors.length)])
        }
    }
  });
});
div {
  height: 40px;
  padding: 10px;
  text-align: center;
  margin-bottom: 10px;
}
#d1 {
  background-color: #00A388;
}
#d2 {
  background-color: #FFFF9D;
}
#d3 {
  background-color: #BEEB9F;
}
#d4 {
  background-color: #79BD8F;
}
<script src="http://scrollrevealjs.org/js/scrollReveal.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>

  <p data-sr>Scroll Reveal-Default</p>


  <!--Enter Properties The enter keyword controls the vector origin (direction) of your animation.-->
  <!-- Reveal with a downward motion -->
  <div class="random-color" data-sr='enter top'>enter top</div>
  <br>

  <!-- The other accepted values... -->
  <div class="random-color" data-sr='enter left'>enter lef</div>
  <br>
  <div class="random-color" data-sr='enter right'>enter right</div>
  <br>
  <div class="random-color" data-sr='enter bottom'>enter bottom</div>
  <br>
  <!--Enter Properties Ends-->

  <!--Move Properties The move keyword controls the distance (in pixels) traveled during animation.-->
  <div class="random-color" data-sr='move 24px'>move 24px</div>
  <!--Enter Properties Ends-->
  Over The over keyword sets the duration (in seconds) of your animation.

  <div class="random-color" data-sr='over 0.6s'>over 0.6s</div>
  <div class="random-color" data-sr='over 1.3s'>over 1.3s</div>
  Flip The flip keyword is a rotation keyword, controlling rotation along the X axis (pitch).

  <div class="d1" data-sr="enter left, hustle 20px">enter left, hustle 20px</div>
  <div class="d2" data-sr="wait 2.5s, ease-in-out 100px">wait 2.5s, ease-in-out 100px</div>
  <div class="d3" data-sr="move 16px scale up 20%, over 2s">move 16px scale up 20%, over 2s</div>
  <div class="d4 random-color" data-sr="enter bottom, roll 45deg, over 2s">enter bottom, roll 45deg, over 2s</div>


</body>

</html>

Answer №2

It appears that you are attempting to apply a mathematical function to a string in your code. The specific scenario you've outlined involves generating a color using three numeric values within a certain range (255-199), and then trying to use this generated color with values like 'red', 'green', etc...

I suggest experimenting with the provided example code to observe the results for yourself.

Answer №3

For optimal performance, try initiating scrollReveal during the document ready event.

 $(document).ready(function() {
    window.sr = new scrollReveal();
})

Your color functionality should already be active within the document ready function.

Best of luck implementing this solution!

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

Selecting the textarea element within a form using jQuery

Here is a code snippet that I've been working with: <!DOCTYPE html> <html> <head> <meta http-equiv='Content-Type' content='text/html;charset=utf-8' /> <script type='text/javascript' sr ...

The background image is not displaying correctly in the tag td

I'm struggling to display a background image inside a table data cell using CSS. <td class='details-control'></td> When I use the following CSS rules, the image is not displayed: td.details-control { background: url(http:// ...

Replacing the useEffect hook with @tanstack/react-query

Lately, I made the decision to switch from my useEffect data fetches to react-query. While my useEffect implementation was working flawlessly, I encountered various issues when trying to directly convert my code for react-query. All the examples I found ...

Issue encountered while retrieving JSON data from Github

I am currently using d3.json to retrieve a JSON link from the Enterprise GitHub (within the same repository/folder as the JavaScript file). d3.json("https://raw.github.exampleEnterprise.com/path/to/repo/data.json?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ...

Issues arising from code that computes percentages

I currently have three boxes in my HTML template that are meant to calculate and display various values. The first box is calculating a score, the second box represents the total amount of points possible, and the third box is supposed to show the percenta ...

`Finding specific components or pages within an AngularJS application`

I came across a unique webpage for an Angularjs based project. I am looking to develop an autofiller and autoclicker feature. To achieve this, I need to identify pages or subpages uniquely (especially in cases of Ajax-based changes). The major challenge ...

What is the solution for correcting the fixed footer in jQuery Mobile?

My experience with jQueryMobile has led me to encounter a couple of persistent bugs even after including data-role="footer" data-position="fixed" in the markup: The footer toggles on a null click event. The footer remains unfixed and ends up hiding some ...

Can you retrieve data or HTML content from the main Vue 3 component?

I have experience using Vue in previous projects but I'm currently facing some challenges on how to pass information/arguments to a root Vue 3 component. My goal is to set up something like this in my HTML: <div class="nav-app" nav=&quo ...

Creating a Composite of Several Boxes in THREE.js

My goal is to display multiple boxes together in a specific structure shown in the image I have attached. I am interested in testing the GPU limitations by increasing the number of boxes, and then later on, I will focus on optimization. The framework I am ...

Avoid updating numerous divs when hovering over them

Creating a brief survey utilizing HTML, CSS, and JavaScript. The goal is to present a question and allow the user to rate it on a scale of 1-5. It would be ideal to have a responsive scale where hovering over 1 turns it yellow, hovering over 2 highlights ...

Error: The code has a syntax issue due to an unexpected "function" token while using

Recently, I decided to try out Node version 6.2.1 with some of my code. My goal was to migrate the hyper-callback oriented codes to a cleaner and potentially more efficient approach. Surprisingly, when I attempted to run the node code in the terminal, an ...

What are the alternatives to invoking a server-side C# method from JavaScript without using a WebMethod or UpdatePanel?

I am looking for alternatives to using an update panel. The common WebMethod approach is causing errors with the code below: private string currentHtml() { StringWriter str_wrt = new StringWriter(); HtmlTextWriter html_wrt = new Htm ...

Achieving a shadow effect above a CSS border: tips and tricks

<div class="row"> some content <div class="info-box"> some other content </div> </div> .row { float: left; margin-bottom: 1.5%; border: 1px solid #e3e3e3; -webkit-border-radius: 4px; -moz-border ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

Material UI fails to display any content

I attempted to integrate a navbar into my website, but React is not displaying anything. Even creating a new project did not resolve the issue. Additionally, Stack Overflow restricts posts that contain mostly code and I am unsure why. Here is my App.js im ...

Utilizing Google Maps autosuggest with JQuery - Trigger load upon selection

Currently, the Google map code operates in the following manner: Upon entering text into the input box, a list of suggestions loads. When you click on one of these options, it places it into the input box. However, you then still need to click "find" to d ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

Three.js - Display a model with material that can be visible without the need for a light source

I am currently utilizing Three.js, specifically version 71. My workflow involves creating models in Blender, exporting them as JSON files, and then using THREE.JSONLoader to incorporate these models into my scene as shown below: this.jsonLoader.load(path ...

Animating CSS Skill Bars

My goal is to create a skill bar that smoothly slides in the background color of the progress while keeping the label for the skill in a fixed position. .skill-container * { box-sizing: border-box; } .skill-container { width: 100%; border-radiu ...

Sorting an array of subdocuments within a populated query result in Node.js with Mongoose

I am looking to fetch recently submitted articles by members based on time. In the Member Schema, there is an array of _id values for submitted articles. Below are the details of the Member and Article Schemas: Member Schema const mongoose = require( ...