Hi everyone,
I am following up on a question from Neil during the office hours on October 3, 2023. The question was about how to properly implement a light and dark mode in WeWeb. There are multiple approaches to managing this topic.
What I consider to be a best practice is to use CSS variables. Here is how you can utilize this powerful feature in the editor:
- First, create two object variables: one for the light colors and another one for the dark colors. As a default value, you need to include all your colors, which we like to refer to as “tokens.” Each key in your objects needs to start with
--
. This is very important. Below is an example
- Then, create another variable that you can name
Color mode
. Remember to toggle Save in local storage, so your users’ browsers remember the value.
- Now create a
global workflow
that you can nameInit CSS variables
- Add a True/False split and bind the condition like this
- Then, add Two
Custom Javascript
actions with this code:
const colors = variables['01232d53-328a-4882-bf10-5a2c64fe2536']; // Update this line
Object.entries(colors).forEach(([label, value])=>{
wwLib.getFrontDocument().documentElement.style.setProperty(label, value);
})
Update the code with your variables like this:
- Now you need to create a workflow that will be triggered
On App Load
. So the initialization appends every time the application loads.
Execute the global workflow you previously created
- Next, you can add a select input in your application. And add a workflow to toggle the color mode and init again the CSS variable.
- Now, you can bind! Select any color property and bind to a string like this
"var(--side-menu)"
Here you are:
My advice is to save your styles in classes (you can save formulas in classes) so you don’t have to type in “var(…)” every time you need to style an element.
I hope this is helpful. Please let me know in the comments.
Cheers!