Color Switcher UI with Color input type & CSS Variables

nirazanbasnet

⚡ Nirazan Basnet ⚡

Posted on January 22, 2020

Color Switcher UI with Color input type & CSS Variables

Alt Text

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:



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


Enter fullscreen mode Exit fullscreen mode

To get more insight into CSS variables you can read my blog on 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

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.



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


Enter fullscreen mode Exit fullscreen mode

Alt Text

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.



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


Enter fullscreen mode Exit fullscreen mode

Alt Text

Configure CSS Variables

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



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


Enter fullscreen mode Exit fullscreen mode

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,



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


Enter fullscreen mode Exit fullscreen mode

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,



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


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

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

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

Till then,
Keep on Hacking, Cheers

💖 💪 🙅 🚩
nirazanbasnet
⚡ Nirazan Basnet ⚡

Posted on January 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related