function makeColorPickerGo(colorInput, colorPalette) { const currentColorInput = colorInput; const currentColorPalette = colorPalette; function hideColorPalette() { if (currentColorPalette.mouseIsOver === false) { currentColorPalette.style.display = 'none'; currentColorInput.style.border = `2px solid ${currentColorInput.value}`; } } function componentToHex(c) { const hex = c.toString(16); return hex.length === 1 ? `0${hex}` : hex; } function rgbToHex(color) { const arr = color .replace('rgb', '') .replace('(', '') .replace(')', '') .split(','); return `#${componentToHex(Number(arr[0]))}${componentToHex( Number(arr[1]), )}${componentToHex(Number(arr[2]))}`; } function chooseColor(e) { const color = rgbToHex(e.target.style.backgroundColor); currentColorInput.value = color; currentColorInput.style.border = `2px solid ${color}`; currentColorPalette.style.display = 'none'; } function showColorPalette() { currentColorPalette.style.display = 'block'; const newDiv = '
'; currentColorPalette.innerHTML = newDiv; const options = document.getElementsByClassName('color-option'); for (let i = 0; i < options.length; i += 1) { options[i].onclick = function handleColorOptionClick(event) { chooseColor(event); }; } } currentColorInput.addEventListener('click', showColorPalette); currentColorInput.addEventListener('focusout', hideColorPalette); currentColorPalette.mouseIsOver = false; currentColorInput.style.border = `2px solid ${colorInput.value}`; currentColorPalette.onmouseover = () => { currentColorPalette.mouseIsOver = true; }; currentColorPalette.onmouseout = () => { currentColorPalette.mouseIsOver = false; }; } const colorInputs = document.getElementsByClassName('color-picker'); const colorPalettes = document.getElementsByClassName('color-palette'); for (let i = 0; i < colorInputs.length; i += 1) { makeColorPickerGo(colorInputs[i], colorPalettes[i]); } window.InstantClick.on('change', () => { const colorInputElements = document.getElementsByClassName('color-picker'); const colorPaletteElements = document.getElementsByClassName('color-palette'); for (let i = 0; i < colorInputElements.length; i += 1) { makeColorPickerGo(colorInputElements[i], colorPaletteElements[i]); } });