Switch the color value from black to red with a click in JavaScript

I am currently developing an app and I'm in the process of creating a function that gradually changes the color from black to red based on a numerical value. For instance, if a user selects a number ranging from 0 to 100, they can click a button up to 100 times until they reach a point where clicking is no longer allowed. As they progress, I want the color to transition from black to full red.

Color Progression: Number 0 = black -> Number 100 = full red

Below is the function for incrementing a number onclick:

<input type="text" id="inc" value="0" readonly="readonly"></input>

i = 0; // Default value shown on counter
x = 0; // Maximum value set by the user

function adicionar()
{
 if( i < x)
 {
  i++;
  document.getElementById('inc').value = i;
 }
}

This is my attempted code logic:

a = x * 50 / 100
b = x * 80 / 100
c = x * 100 / 100

if(i == a){
 var $$ = Dom7;
 $$('body').addClass('yellow');
}
if(i == b){
 var $$ = Dom7;
 $$('body').addClass('red');
}
if(i == c){
 var $$ = Dom7;
 $$('body').addClass('red2');
}

Thank you for your assistance!

Answer №1

let userNumberChoosen = 10 //assuming the value ranges from 0 to 10, but can be any number
let start = 0;
const changeColor = () => {
    const r = 255 * start/userNumberChoosen;
    const b = 0;
    const newColor ='rgb('+r+','+b+',0)';
document.getElementById("change").style.backgroundColor = newColor;
  start += 1;  //increment color step
}
<html>
  <body>
    <div> Pay attention to my background color </div>
    <div id="change">.</div> 
    <button onClick="changeColor()">Alter background</button>
  </body>
  
</html>

Answer №2

Give this a try, assuming x represents the limit, the function getRed will provide a shade of red.

let i = 0, x = 100;
document.getElementById("btn").addEventListener ('click', () => {
  add ()
});
function getRed ( index, limit ) {
    return Math.floor(index*255/limit);
}
function add() {
  if( i < x ) {
      i++;
      const inp = document.getElementById('inc');
      inp.value = i;
      const red = getRed ( i, x );
      inp.style.color = `rgb(${red},0,0)`;;
  } else {
    alert('limit exceeded');
  }
}

Answer №3

const maxLength = 500;
const textLength = inputText.length; 

const percentageRemaining = ((maxLength - textLength) * 10) / maxLength;
const greenBlueValue = 15.2 * percentageRemaining;
const colorShift = `rgb(152, ${greenBlueValue}, ${greenBlueValue})`; 
//color transitions from gray to red

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

Struggling with incorporating a view using ui router

Currently, I'm working my way through the MEAN stack tutorial on Thinkster, and encountering a few challenges along the way. The initial hurdle I faced was with inline views. I attempted to use a script tag with an id of "home.html" and route it usin ...

Are your Fixed Action Buttons experiencing issues?

Currently, I am in the process of learning Materialize (materializecss.com) but have hit a roadblock when it comes to creating action buttons. The issue at hand is that while the button on the lower left-hand corner displays properly, the other buttons fai ...

Security measures within the browser are blocking access to the same-domain Ajax request made using jQuery, resulting in an "Access is

While attempting to submit a form using jQuery's $.post method, I am encountering the SCRIPT5: Access is denied. error specifically in Internet Explorer. Despite the common belief that this error is linked to cross-domain requests, my own request does ...

What is the best way to enlarge a Material UI card?

Currently, I am utilizing Material UI version 4 on my website and integrating cards (for more details, click here). https://i.stack.imgur.com/dm2M2.png I am interested in enlarging the overall size of the card so that the image appears larger. As I am si ...

How to retrieve the id of a different view using Backbone

On one of my views, there is a search box with a "Search" button that has an id of "search". In another view, I want to perform a search when the "Search" button is clicked. However, in order for this to work, I need to access the id. How can I accomplish ...

Ways to check if an array is empty in Typescript

Every time I attempt to log in, the first thing I do is validate the search data stored in the database by querying information from a matrix. This code can be found in login.controller.ts export async function postLogin(req: Request, res: Response): Pro ...

CSS issue encountered: "Value of property is not valid"

When working with CSS, I encountered an error stating "Invalid Property Value" while inspecting the transform element of the Service section in the Wall Street theme. Could someone kindly assist me with the necessary steps to rectify this issue? https://i ...

Attempting to embed a Java applet into an HTML document

Here is how the directory looks: test.html blah hmmm In the "blah" directory, we have all the applet files, including blahBlah.class. In the "hmmm" directory, there are additional class files taken from a library or similar source that are also used by t ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Sending a prop to a handler causes issues with navigation paths

I'm facing an issue with my handler and button component setup. Here's my handler: const addToCartHandler = (id) => { navigate(`/cart/${brand}/${id}?qty=${qty}`)}; And here's the button component using the handler: <Button onClick={a ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

Experiencing difficulty when attempting to save a zip file to the C drive

I came across this code snippet on SO and decided to use it for my project. The goal is to send a simple 1.5mb zip file and save it on my C drive by making a request through Postman with the binary option enabled, sending the zip file to localhost:3012. c ...

What are some ways I can receive a response promptly from a service in AngularJS?

After calling the service method from the controller, there is a delay in receiving the data that I need to populate a dropdown. My expectation is that when I call this method from the controller, it should return a response immediately, and then other log ...

Organizing items within a group

As I embarked on my journey of creating my first Meteor app, I encountered a challenge that left me feeling a bit lost. I have a collection of Entries and I want to categorize them by date, not simply sort them. Each entry comes with a date and I envision ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

Enhance JSON object with texture using three.js

I've successfully created a 3D model using Blender. After exporting it with the Three.js exporter and loading it in JavaScript, everything seems to be working fine except for one issue - the texture is not being displayed properly. I made sure to add ...

JavaScript: Show Loading Screen until certain assets are fully loaded

Just a quick overview. I currently have a loading screen that appears before the website finishes loading for a specified time. What I'm looking to achieve is a method to check if certain elements are loaded and then remove the loading screen, rathe ...

Node Js enables the establishment of a unique connection between one entity to

How can I retrieve all of the photos associated with the currently logged-in user using their session_id? I have a table named photos that stores the images for each user, with columns like: id | user_photos | user_id (Foreign Key) let select_photos_sql ...

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...