Color Switcher UI with Color input type & CSS Variables
Tags: cssvariables, codepen, javascript, css
Published: 2020-01-22 10:16:10

---
title: Color Switcher UI with Color input type & CSS Variables
published: true
description: 'With the help of the CSS variables and native color input type, we can switch the theme UI on our web application or site. Well, the web is moving fast so we can use CSS variables which supports many of the modern browsers. **CSS variables** are readable code that provides ease of change across large documents and many more.'
cover_image: https://thepracticaldev.s3.amazonaws.com/i/tqd45llc5hng61lc2msf.png
tags: ["css-variables", "codepen", "javascript", "CSS"]
---

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/tqd45llc5hng61lc2msf.png)

With the help of the CSS variables and native color input type, we can switch the theme UI on our web application or site. Well, the web is moving fast so we can use CSS variables which supports many of the modern browsers. **CSS variables** are readable code that provides ease of change across large documents and many more.

Example:

```css
:root {  
   --font-size: 20px
}
.test {  
   font-size: var(--font-size)
}
```

To get more insight into CSS variables you can read my blog on [Understanding CSS Variables.](https://blog.yipl.com.np/understanding-css-variables-74fdb6e7ef54 "Understanding CSS Variables.")

On the other hand, we have the `<input type=color>` which defines a color picker input field. A color picker will be visible where we can click and select a color that can then be passed as an input.

Example:

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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8w0p13viovmpl28owyer.gif)

As this is a native input field, the UI of the color picker may vary on the different operating systems. The demo color picker example is from Mac OS. With this, we are not forced to use any javascript plugins which is great.

## **So, let's create a Custom UI theme,**

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

```html
<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>
```

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/58w6887bosi8zt0ebf20.png)

Now, we need to store the default color values for this we are using `data-bg-color` and `data-color` attributes.

## **For the dynamic colors**
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.

```html
<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>
```

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/41pcf4tx95openvj9cin.png)

## **Configure CSS Variables**
We set the CSS variables and their default values. For this, we use `:root` pseudo-class.

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

We have set two variables `primary-bg-color` and `primary-color`. By default, the background theme is dark blue and the text color is white.

## **Using The CSS Variables**
Now if we want to change the `background-color` and the `color` element our CSS structure looks like this,

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

The CSS variable is set to an element by using the var function. With this, we can change the variable and the value for these properties will be updated automatically.

## **Javascript in action**
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.

At first, Let’s create the theme update function,

```javascript
const handleThemeUpdate = (cssVars) => {
    const root = document.querySelector(':root');
    const keys = Object.keys(cssVars);
    keys.forEach(key => {
      root.style.setProperty(key, cssVars[key]);
    });
}
```

This function takes an object as a parameter and for each key update, the corresponding CSS variable defined on the :root pseudo-class. To achieve this, we need to define the object in a way where each key represents the CSS variable name and each key-value represents the actual CSS value we want to apply.

Now, we need to find the elements and attach the event handlers:

```javascript
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
      });
    });
  });
```

Now when the user clicks on a `span` element the values of the data attributes are stored and set to their respective CSS variables.

And same for the color-picker, when a user changes the value of the color-picker element, the selected value is set to the corresponding CSS variable.


**Codepen** Demo [here](https://codepen.io/nirazanbasnet/full/OeZpjo "here")

## **Conclusion**
By coming this far I hope you get the idea of how we can change the theme color dynamically on a website. I suggest you experiment with this feature in your project and enjoy!

I hope you’ve found this blog very helpful. Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions.

Originally posted on medium [here](https://codeburst.io/color-switcher-ui-with-color-input-type-css-variables-d4efd8aa6f8f "here")

Till then,
Keep on Hacking, Cheers