Updating linear gradient using JavaScript (React)

Is there a simple way to update a linear gradient background using javascript? Right now i have it like this in my CSS:
:root {
--bg-gradient: linear-gradient(
25deg,
hsl(240deg 15% 13%) 0%,
hsl(233deg 22% 15%) 11%,
hsl(226deg 30% 17%) 23%,
hsl(221deg 40% 18%) 36%,
hsl(215deg 52% 19%) 48%,
hsl(221deg 62% 26%) 61%,
hsl(238deg 46% 36%) 74%,
hsl(264deg 54% 40%) 87%,
hsl(287deg 84% 36%) 100%
);
}
body {
background-image: var(--bg-gradient);
}
:root {
--bg-gradient: linear-gradient(
25deg,
hsl(240deg 15% 13%) 0%,
hsl(233deg 22% 15%) 11%,
hsl(226deg 30% 17%) 23%,
hsl(221deg 40% 18%) 36%,
hsl(215deg 52% 19%) 48%,
hsl(221deg 62% 26%) 61%,
hsl(238deg 46% 36%) 74%,
hsl(264deg 54% 40%) 87%,
hsl(287deg 84% 36%) 100%
);
}
body {
background-image: var(--bg-gradient);
}
and the idea is to update the --bg-gradient var to any valid gradient string that i take in from user input. this was my initial idea:
// from input
const editBgGradient = `linear-gradient(
45deg,
hsl(240deg 100% 20%) 0%,
hsl(290deg 100% 29%) 23%,
hsl(340deg 100% 37%) 46%,
hsl(30deg 100% 46%) 66%,
hsl(47deg 95% 56%) 82%,
hsl(31deg 82% 66%) 91%,
hsl(16deg 60% 75%) 97%,
hsl(0deg 17% 83%) 100%
)`

// run as an event handler
const saveBgGradient = () => {
document.documentElement.style.setProperty("--bg-gradient", editBgGradient);
setTree({ ...tree, bgGradient: editBgGradient });
};
// from input
const editBgGradient = `linear-gradient(
45deg,
hsl(240deg 100% 20%) 0%,
hsl(290deg 100% 29%) 23%,
hsl(340deg 100% 37%) 46%,
hsl(30deg 100% 46%) 66%,
hsl(47deg 95% 56%) 82%,
hsl(31deg 82% 66%) 91%,
hsl(16deg 60% 75%) 97%,
hsl(0deg 17% 83%) 100%
)`

// run as an event handler
const saveBgGradient = () => {
document.documentElement.style.setProperty("--bg-gradient", editBgGradient);
setTree({ ...tree, bgGradient: editBgGradient });
};
But nothing happens when this function runs - the variable isn't updated. I'm guessing it can't parse the string as a linear-gradient function or whatnot? I saw this but that looks like a hassle: https://www.w3schools.com/tags/canvas_createlineargradient.asp. Is there any other way? Seems like a simple problem
4 Replies
cornflour
cornflour2y ago
hmm but when I tested that code it does work though? Is there any other element at play that might make it not work here?
julius
juliusOP2y ago
oh it seems like it breaks if there is an ending ; to the string...
julius
juliusOP2y ago
works without it 🙂
julius
juliusOP2y ago
some extra parsing logic to accept more formats and it works as expected 👍
Want results from more Discord servers?
Add your server