JavaScript and modifying color using hexadecimal color codes

Being a novice in front-end development, I embarked on a project using JavaScript that would alter the color of a div based on environmental parameters such as temperature and pressure. My initial idea involved creating buttons to adjust the temperature - one for increasing it and one for decreasing it - with the colored div reflecting these changes. The goal was to have the div shift towards red hues as the temperature rose and towards blue hues as it dropped, akin to a color mixer tool available on the w3schools site here, all while utilizing hex color values. However, I encountered an issue when attempting to implement hex color values in my code; it simply didn't function correctly. Curiously, when I used integer values for other manipulations, like adjusting the height of the div dynamically via button clicks, it worked flawlessly. This discrepancy puzzled me as I sought out similar JavaScript projects concerning color sliders or gauges, and scoured through related queries on coding forums, yet found no solution.

<html>
    <head>
         <style>
            #cool{
                background-color:lightblue;
                float:left;
            }
            
            #hot{
                background-color:red;
                float:right;
            }
            
            button{
                width:200px;
                height:100px;
                font-size:20pt;
            }
            
            #range{
                width:100%;
                height:50px;
                background-color:#ff0000;
            }
         </style>
    </head>
    
    <body>
        <div id="range">   </div>
        <button id="hot" type="button" onclick="tempUp()"> hot  </button>
        <button id="cool" type="button" onclick="tempDown()"> cool </button>
        
    </body>
    
    <script>
        var colorVal = [ff0000,b2004c,5900a6,0000ff]; //from red to blue
        var i = 0; //default value
        
        function tempUp(){
            if(i < 3){
                i++;
                document.getElementById('range').style.backgroundColor = colorVal[i];
            }
         }
         
         function tempDown(){
            if(i > 0){
                i--;
                document.getElementById('range').style.backgroundColor = colorVal[i];
            }
         }
    </script>
</html>

I experimented with converting hex color values to decimal, but unfortunately, that approach proved futile.

Answer №1

Great job! You're very close to the correct solution, just a few adjustments needed:

  1. There are some errors in your colorVal array:
  • The order of your colorVal array is incorrect: When you increase with tempUp(), the index also increases, but the colors should transition from blue to red instead of red to blue.
  • Make sure to add the prefix # before the hex values.
  • Enclose the hex values in quotes for string representation.

You can consider this revised array:

var colorVal = ["#0000ff", "#5900a6", "#b2004c", "#ff0000"];

This sequence goes from blue to red.

  1. The initial value of i should start at index 3 due to the reversed array order. If you prefer, you can reverse the array back to red to blue and set the starting index as 0.

Check out this corrected code snippet:

var colorVal = ["#0000ff", "#5900a6", "#b2004c", "#ff0000"]; //from red to blue
var i = 3; //default value

function tempUp() {
  if (i < 3) {
    i++;
    document.getElementById('range').style.backgroundColor = colorVal[i];
  }
}

function tempDown() {
  if (i > 0) {
    i--;
    document.getElementById('range').style.backgroundColor = colorVal[i];
  }
}
#cool {
  background-color: lightblue;
  float: left;
}

#hot {
  background-color: red;
  float: right;
}

button {
  width: 200px;
  height: 100px;
  font-size: 20pt;
}

#range {
  width: 100%;
  height: 50px;
  background-color: #ff0000;
}
<body>
  <div id="range"> </div>
  <button id="hot" type="button" onclick="tempUp()"> hot  </button>
  <button id="cool" type="button" onclick="tempDown()"> cool </button>

</body>

Answer №2

If you're looking for a more appropriate method in this scenario, the hexadecimal format might not be your best option.
Instead, consider utilizing HSL, where color is determined by the hue ranging from 0 to 360° like so:

For instance, when transitioning a color gradient from blue to red on a gauge, simply adjust the hue from 225 to 0°.

Answer №3

If you prefer using hexadecimal values, consider the following approach (though converting directly from decimal values does not require base conversion):

var current = "#ff0000"

/*adjust the increment value to control the speed of color change*/
const increment = 12;


function increaseColor(color, quantity) {
/*use a positive quantity for warmer colors and a negative quantity for cooler ones*/

/*since blue is typically darker, it's mixed with some green to cool down*/

/*convert red and blue to decimals and apply the increment*/
  let red = parseInt(color.substring(1,3),16) + quantity;
  let green = parseInt(color.substring(3,5),16) - parseInt(quantity/1.5);
  let blue = parseInt(color.substring(5,7),16) - quantity;

/*stop increasing when reaching the maximum limit*/
  if (red > 255) {
    red = 255;
    green = 0;
    blue = 0;
  }
  if (red < 0) {
    red = 0;
    green = 170;
    blue = 255;
  }
  
/*convert the result back to hex*/
  red = red.toString(16);
  green = green.toString(16);
  blue = blue.toString(16);
  if(red.length==1) red='0'+red;
  if(green.length==1) green='0'+green;
  if(blue.length==1) blue='0'+blue;
  
  return "#" + red + green + blue;
}


function increaseTemperature() {
/*update the current color*/
  current
   = increaseColor(current, increment);
/*update the background*/
   document.getElementById('range').style.backgroundColor = current;
}


function decreaseTemperature() {
  /*update the current color*/
  current
   = increaseColor(current, -1*increment);
/*update the background*/
   document.getElementById('range').style.backgroundColor = current;
}
#cool{
                background-color:lightblue;
                float:left;
            }
            
            #hot{
                background-color:red;
                float:right;
            }
            
            button{
                width:200px;
                height:100px;
                font-size:20pt;
            }
            
            #range{
                width:100%;
                height:50px;
                background-color:#ff0000;
            }
<html>
    <head>
    </head>
    <body>
        <div id="range">   </div>
        <button id="hot" type="button" onclick="increaseTemperature()"> hot  </button>
        <button id="cool" type="button" onclick="decreaseTemperature()"> cool </button>
        
    </body>
</html>

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

Navigating through child elements within a div using JavaScript

I recently coded a div using this snippet... let sidebarBox = document.createElement("div"); sidebarBox.id = "sidebarBox"; ...and then I created a second div like so... let sidebarAd = document.createElement("div"); sidebarAd.className = "sidebarAd"; B ...

Struggling with Implementing a Hollow Button in Bootstrap 3

Could you please review This Demo and provide guidance on how to remove the grey background color when clicking on the button? I attempted the following: .btn-hallow:hover{ background: none; color: aliceblue; } .btn-hallow.active:focus{ backg ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Tips for Enhancing Window Leveling (Brightness and Contrast)

const pixelArray = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11..] if (pixelArray != null) { for (let i = 0; i < pixelArray.length; i++) { let ...

various stunning galleries accessible from a single page of thumbnail images

I'm trying to create a unique gallery experience on my website. I have a set of 6 images, each featuring a different house. What I want is for each image, when clicked, to open up a fancybox gallery showcasing 4 more detailed photos of the same house. ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Using Javascript to make an AJAX request and appending "?=####" to the end of the call

When I make an ajax call to a URL on my server, the response from my logs shows as "/action?_=1423024004825". Is there a way to remove this extra information? $.ajax({ type: "GET", url: "/action" }); ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

Integrating jQuery into the functions.php file of a Wordpress

I have been using a jQuery script in Unbounce and now I want to implement it on my Wordpress page. I believe I will have to insert this into the child theme functions file, but I know it requires some PHP code as well. As I am still fairly new to this proc ...

Modify the role attribute on elements in real-time to enhance accessibility

On a German website, we have implemented a textfield with autocomplete functionality in a form. As the user types into the input field, a dropdown menu of suggestions appears for them to select from. It is crucial that this feature is fully accessible with ...

When hovering over the element, child elements remain unaffected by the wrapping behavior

My anchor tag contains a span and an image, but I am having trouble making them hover together. <a href=""> <img src="image"/> <span>Shopping Cart</span> </a> a :hover { opacity: 0.6; } Check out the fiddle ...

Ways to transfer information from a directive to a controller

In my application, I have created a custom directive that utilizes D3.js. The goal is to trigger an API call to fetch more data when a user clicks on a node within the D3 visualization. This involves accessing the data linked to the clicked node and sendin ...

An interactive 3D model emerges against a sleek ebony backdrop on my online platform

I stumbled upon a three.js 3D object featuring a unique touch - a 404 text with a floating orb replacing the zero. Upon importing its code, it rendered successfully, albeit against a black background. Despite my efforts to tweak values and apply background ...

Material-Table React with a Fixed Header

After examining this specific example, I have a query regarding a sticky header feature. Here is the example link: https://material-table.com/#/docs/features/fixed-columns I have been attempting to make the header from 'Name' to 'BirthPlace ...

What is the best way to validate the accuracy of an HTML form response by using PHP through $.post, all while keeping the answer confidential?

Currently, I am working on a fill-in-the-blank quiz. In my PHP file named index.php, my objective is to validate the user's input against the correct answer stored in my MySQL server. One approach I considered was to simply echo the answer using < ...

The error message "Unable to map props.theTodos" is displayed

I'm facing an error message while compiling: "TypeError: props.theTodos.map is not a function". I've been struggling with this issue for quite some time, but I haven't found a solution yet as I'm using hooks instead of class components. ...

Responsively center text vertically

I am facing a challenge with two divs that are floating next to each other: one contains a large headline text, and the other has a photo with a caption. My objective is to ensure that the headline text is vertically centered regardless of the height of th ...

Center and align pictures within a stationary container

I am working on a simple webpage that has a fixed footer. In this footer, I want to have 5 images centered with equal distances between them. Below is my HTML/CSS : Footer div : div.fixed { position: fixed; bottom: 0; right: 0; width: ...

Applying a class in jQuery to an element when the data attribute aligns with the current slide in Slick

I need to compare the data-group attribute of the current slide to the equivalent attribute in a navigation list. If they match, the anchor element in the navigation list should be given an active class. How can I achieve this using jQuery? Navigation Li ...

The requested resource does not have the 'Access-Control-Allow-Origin' header in nginx

Although I have come across many similar questions, none of them have helped me solve my specific problem. jQuery.post( 'http://example.com/api_offer/get_time_left', function(data) { console.log('get time'); }, 'json'); ...