Skip to content

Instantly share code, notes, and snippets.

@tzi
Last active November 24, 2016 11:14
Show Gist options
  • Save tzi/39472a37237521e8fd454c4adc400cd3 to your computer and use it in GitHub Desktop.
Save tzi/39472a37237521e8fd454c4adc400cd3 to your computer and use it in GitHub Desktop.
Extract the color combination from a web page
(() => {
// Settings
const debug = false;
const maxDepth = false;
const rootElementSelector = false;
// Result
const refList = [];
const output = document.createElement('div');
// Utils
const isAlreadyReferenced = newRef => refList.some(ref => Object.keys(newRef).every(key => newRef[key] === ref[key]));
const walk = (node, parentBackgroundColor = 'rgb(255, 255, 255)', depth = 0) => {
let {color, backgroundColor} = window.getComputedStyle(node);
if (backgroundColor == 'transparent') {
backgroundColor = parentBackgroundColor;
}
const styles = {color, backgroundColor};
if (!isAlreadyReferenced(styles)) {
if (debug) {
console.log(styles, `${node.tagName}${[...node.classList].map(s=>`.${s}`).join('')}`);
}
refList.push(styles);
}
if (!maxDepth || depth < maxDepth) {
[...node.children].forEach(el => walk(el, backgroundColor, depth + 1));
}
};
// Let's go!
walk(rootElementSelector ? document.querySelector(rootElementSelector) : document.documentElement);
refList.forEach(ref => {
const el = document.createElement('div');
el.setAttribute('style', `float: left; margin: 0.5em 1em; padding: 0.5em 1em; color: ${ref.color}; background-color: ${ref.backgroundColor}`);
el.innerHTML = 'Lorem Ipsum';
output.appendChild(el);
});
output.setAttribute('style', `position: fixed; top: 0; left: 0; right: 0; z-index: 999999; padding: 0.5em 0; background: white;`);
document.body.appendChild(output);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment