[Solved] How can I make my JavaScript code more DRY? [closed]


Assuming the myFunction series of functions aren’t used elsewhere, you’d do:

var addChangeListener = function(elem, hexInput) {
    elem.onchange = function() {
        hexInput.value = elem.value;
    }
};

const elements = { 'colorpicker01':'hexinput01', 'colorpicker02':'hexinput02', 'colorpicker03':'hexinput03'}

for(elemName in elements) {
    const elem = document.getElementById(elemName);
    const hexInput = document.getElementById(elements[elemName]);
    addChangeListener(elem, hexInput);
}

And if you need to reuse the myFunction functions as well, it’s easy enough to define them at runtime too.

4

solved How can I make my JavaScript code more DRY? [closed]