I’m developing a web app and I need to change the background gradients based on the styles of buttons in our design. Each button has a gradient that uses two colors, and I want to use JavaScript to obtain these colors to create a new gradient for the background.
For instance, our button is styled like this:
.button-standard {
background: linear-gradient(to bottom, #c0a012 0%, #7a5b00 100%);
}
I intend to take the lighter color from this gradient while replacing the darker one with white. Additionally, I want to reverse their positions to achieve the desired outcome:
html {
background: linear-gradient(to bottom, #ffffff 0%, #c0a012 100%);
}
I’ve come across some JavaScript that gets the button’s computed style:
const btn = document.querySelector('.button-standard');
const style = window.getComputedStyle(btn);
console.log(style.backgroundImage);
document.body.style.backgroundImage = style.backgroundImage;
While this code duplicates the gradient, I need to extract the specific colors, switch their order, and replace the darker shade with white. What’s the best approach to achieve this color adjustment using JavaScript?
I hit the same issue building a theme switcher. Regex works but breaks easily with different gradient formats. I found it’s way more reliable to parse the gradient string step by step. Extract the background image, split by commas, then do a thorough color extraction that handles hex and rgb values. To figure out which color’s darker, convert both to RGB and calculate luminance with the standard formula (0.299R + 0.587G + 0.114*B). Replace whichever has lower luminance with white. This approach works consistently across browsers and gradient formats. Also consider caching the computed gradients if you’re doing this a lot - saves on performance.
totally! regex is a solid way to do this. just use style.backgroundImage.match(/#[a-f0-9]{6}/gi) to get the colors, swap em, and replace the darker one with #ffffff. you’ll have your gradient in no time!
I’ve done this before and a simple split approach works great. Grab the background image string, then pull out the hex values - just look for # followed by 6 characters. Convert both colors to decimal and add up the RGB values. Whichever sum is higher is your lighter color. Then build your new gradient string with template literals: linear-gradient(to bottom, #ffffff 0%, ${lighterColor} 100%). It’s straightforward and you don’t need fancy luminance calculations. Won’t be perfect for edge cases where colors have similar brightness, but it gets the job done.