Color Switcher UI with Color input type & CSS Variables

<input type="color" name="favcolor" value="#FFFFF">

So let’s create a Custom UI theme,

First, we need to create the buttons, for example, we can use three span elements.

<span data-bg-color="#b84130" data-color="#ffffff"
style="background-color: #b84130"></span>
<span data-bg-color="#363d98" data-color="#ffffff"
style="background-color: #363d98"></span>
<span data-bg-color="#FFD5CD" data-color="#333333"
style="background-color: #FFD5CD"></span>

To get user-defined theme colors, we are using the input element with a type of color . This enables us to have a fully functional color picker on the web page.

<div>
<label>Background:</label>
<input class="input-color-picker" type="color"
data-id="
bg-color" name="Background">
</div>
<div>
<label>Color:</label>
<input class="input-color-picker" type="color"
data-id="
color" name="Color">
</div>

We set the CSS variables and their default values. For this, we use :rootpseudo-class.

:root {
--primary-bg-color: #400080; // Dark Blue Color
--primary-color: #ffffff; // White Color
}

Now if we want to change the background-color and the color element our CSS structure looks like this,

.hero {
background: var(--primary-bg-color);
color: var(--primary-color);
}

So with the use of javascript, we can achieve the overall functionality of dynamic UI theme switching. So when the user changes the color from the color input field the CSS variables property should be changed automatically.

const handleThemeUpdate = (cssVars) => {
const root = document.querySelector(':root');
const keys = Object.keys(cssVars);
keys.forEach(key => {
root.style.setProperty(key, cssVars[key]);
});
}
const themeSwitchers = document.querySelectorAll('span');
const dynamicInputs = document.querySelectorAll('input.input-color-picker');

const handleThemeUpdate = (cssVars) => {
const root = document.querySelector(':root');
const keys = Object.keys(cssVars);

keys.forEach(key => {
root.style.setProperty(key, cssVars[key]);
});
}

themeSwitchers.forEach((item) => {
item.addEventListener('click', (e) => {
const bgColor = e.target.getAttribute('data-bg-color')
const color = e.target.getAttribute('data-color')

handleThemeUpdate({
'--primary-bg-color': bgColor,
'--primary-color': color
});

$("input.input-color-picker[data-id='color']").val(color)
$("input.input-color-picker[data-id='bg-color']").val(bgColor)
});
});

dynamicInputs.forEach((item) => {
item.addEventListener('input', (e) => {
const cssPropName = `--primary-${e.target.getAttribute('data-id')}`;
handleThemeUpdate({
[cssPropName]: e.target.value
});
});
});