Discovering the process of deriving a deeper shade hex color

When using this particular solution to calculate the darker range of a color, I encountered an issue where the output does not seem to be the correct Hex value as it is missing one part.

> #84079

I'm wondering what mistake I might be making in my approach?

function LightenDarkenColor(col, amt) {
  
    var usePound = false;
  
    if (col[0] == "#") {
        col = col.slice(1);
        usePound = true;
    }
 
    var num = parseInt(col,16);
 
    var r = (num >> 16) + amt;
 
    if (r > 255) r = 255;
    else if  (r < 0) r = 0;
 
    var b = ((num >> 8) & 0x00FF) + amt;
 
    if (b > 255) b = 255;
    else if  (b < 0) b = 0;
 
    var g = (num & 0x0000FF) + amt;
 
    if (g > 255) g = 255;
    else if (g < 0) g = 0;
 
    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  
}
var firstColor = LightenDarkenColor("#3068A1", -20); 
var NewColor = LightenDarkenColor(firstColor, -20); 

console.log(NewColor);

Answer №1

Modify this:

(usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

to read like this

(usePound?"#":"") + ('00000'+(b | (g << 8) | (r << 16)).toString(16)).slice(-6);

This adjustment ensures there are always 6 digits and it rectifies the incorrect positions of green and blue from the original text.

  • (r << 16) shifts red to bits 32 to 47
  • (g << 8) shifts green to bits 16 to 31
  • and b keeps blue in bits 0-15.

UPDATE

It was noted that the values of variables b and g were being incorrectly assigned. To address this, make the following change:

var g = ((num >> 8) & 0x00FF) + amt;

var b = (num & 0x0000FF) + amt;

Adjust where b and g retrieve their values.

If you prefer not to swap those, then update my initial code to this:

(usePound?"#":"") + ('00000'+(g | (b << 8) | (r << 16)).toString(16)).slice(-6);

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

What is the best way to retrieve a specific value from a nested array that is within an array of objects

My goal is to extract a specific field value from a nested array within an object array. Using the map method, I attempted to achieve this but ended up with two empty arrays nested inside two empty objects. Though I am aware of this mistake, it indicates t ...

Is there a way for me to send a freshly created excel file for download using link_to with remote: true?

Is there a way to download a generated excel file in a Ruby on Rails application? After a user clicks on a link, I want to generate an excel file in the backend and have it formatted correctly. However, when I use remote: true in link_to, the file doesn&a ...

Adjusting the inner div dimensions to be 100% of the body's size without relying on the parent div using JavaScript

I have a main layer with multiple layers stacked on top of it. I need the second layer to extend its width to match the body's width. Main Project: http://example.com What I've tried: I looked into: Solution for matching div width with body ...

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

Why aren't functions included when casting from a JSON literal to a specific type?

In my model class, the structure looks like this: export class Task { public name: string; public status: string = "todo"; public completeTask(): void { this.status = "done"; } } There is also a service responsible for retrie ...

Utilizing ReactJS and PHP in Harmony

I'm currently facing issues with establishing communication between a fetch call in React and a PHP script running on my MAMP server. Unexpectedly, I am encountering errors that I am unable to troubleshoot effectively. This snippet depicts the code ...

Transforming a collection of nested objects from Firebase into an array in JavaScript/Typescript

In my Ionic3 / Angular4 application, I am utilizing Firebase. The structure of the data in Firebase Realtime Database is as follows: Using the TypeScript code below, I am fetching observable data from Firebase... getDishesCategories(uid: string) { ...

Jquery is unable to detect duplicate class names

if ($(".event_list")[0]){ if($(".event_list").find(".type").length == 0 && $(".event_list").find(".sold").length == 0) { $(".event_list").click(); } } else { $('#something').click(function() { location.reload(); }); } I attemp ...

Cease the video playback in the modal when the modal is closed

I've attempted several solutions found on stack overflow, but none of them seem to be effective. When I replace the video tag with an iframe, some solutions work, but the video autoplays again, causing issues with the solution. <div class="ico ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

Combining React Components and HTML Elements

I've always been puzzled by the prevalence of using components in React examples. For instance, consider a scenario where I only need to combine some basic HTML with my components: class Homepage extends Component { render() { return ( &l ...

Switch effortlessly between various THREE.EffectComposer scenes with a single renderer in three.js

Currently, I'm experimenting with creating intricate scenes using Composer in three.js. I'm curious to know if it's achievable to switch between two scenes with distinct composer effects applied to them. To better understand this concept, I& ...

Shopping cart feature in PHP - Ajax response only functioning once

I'm in the process of developing a shopping cart. I start by adding products to the cart, then use Ajax to dynamically update the quantity when it changes. Everything works smoothly after the first change, but subsequent quantity updates do not refres ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

Tips for sorting data by date in Angular 4

Seeking guidance on how to filter records in a table based on the date column. The current filtering code is generating an error message: ERROR TypeError: Cannot read property 'indexOf' of null temp = [{ "firstName":"Ravi", "date":"2019-04-0 ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

What is the best way to convert my MySQL data into JSON in a specific format?

I need help with outputting MySQL data into various formats below: timelist, usersex, and userage from the users table. <script type="text/javascript"> timeList = new Array(), userSex = new Array('female','male','male') ...

How to Arrange AppBar Elements in Material UI with React

I'm struggling to align the CloseIcon to be at the end of the container using flex-end but I can't seem to locate where to apply that style. import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/sty ...

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...