@lukeboyle/sync-vars

1.0.1 • Public • Published

Sync Vars

In a recent project I found myself setting colour theme variables in my JavaScript. To reduce double handling, I was setting the theme colours like this:

const themeColors = {
	primary: {
		hex: '#2196f3',
		color: 'blue'
	},
	secondary: {
		hex: '#F44336',
		color: 'red'
	}
};

This object was being passed to vue-material to set the theme colours in there, and then I used the function to set my CSS Variables on my root element.

Installation

Yarn

  • yarn add @lukeboyle/sync-vars

npm

  • npm install @lukeboyle/sync-vars

API

syncVars

Argument Type Example
element HTMLElement document.querySelector('html')
varName String primary-color
varValue String #FEFEFE

Usage

import syncVar from '@lukeboyle/sync-vars'

const vars = {
  'primary-color': 'green',
  'primary-border': 'blue'
};

Object.entries(vars).forEach(([varName, varValue]) => {
    syncVar(document.querySelector('html'), varName, varValue);
});

CSS Variable Test

The package comes bundled with a feature test for css variables. You can use it like this:

< IE11

import syncVar, { testCSSVariables } from '../../../src/index';

function init() {
  // If you give testCSSVariables a function, it will return a bool of the test result
  testCSSVariables(response => {
    if (response) {
      import syncVar from '@lukeboyle/sync-vars'
      
      const vars = {
        'primary-color': 'green',
        'primary-border': 'blue'
      };
      
      Object.entries(vars).forEach(([varName, varValue]) => {
          syncVar(document.querySelector('html'), varName, varValue);
      });
    } else {
      console.warn('color-sync: You are using a browser that does not support CSS Variables, upgrade your browser for the full power');
    }
  });
}

window.addEventListener('load', init);

> IE11

import syncVar, { testCSSVariables } from '../../../src/index';

function init() {
  testCSSVariables().then(
    () => {       
      syncVar(document.querySelector('html'), 'primary-color', 'red');
    },
    error => {
        console.warn(error);
        // 'color-sync: You are using a browser that does not support CSS Variables, upgrade your browser for the full power'
    }
  );
}

window.addEventListener('load', init);

Results in

<body style="--primary-color: green; --primary-border: blue;">
  ...
</body>

Coming Soon

  • Keep CSS variables in sync with Javascript

Package Sidebar

Install

npm i @lukeboyle/sync-vars

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • lukeboyle