My code looks pretty untidy, because I'm not really used to coding in JavaScript. In PHP, I would use a for loop and dynamic variables, but I can't get dynamic variables to work in JavaScript.
How would you DRY this up?
document.getElementById("colorpicker01").onchange = function() {myFunction01()};
function myFunction01() { hexinput01.value = colorpicker01.value;}
document.getElementById("colorpicker02").onchange = function() {myFunction02()};
function myFunction02() { hexinput02.value = colorpicker02.value;}
document.getElementById("colorpicker03").onchange = function() {myFunction03()};
function myFunction03() { hexinput03.value = colorpicker03.value;}
document.getElementById("colorpicker04").onchange = function() {myFunction04()};
function myFunction04() { hexinput04.value = colorpicker04.value;}
document.getElementById("colorpicker05").onchange = function() {myFunction05()};
function myFunction05() { hexinput05.value = colorpicker05.value;}
document.getElementById("colorpicker06").onchange = function() {myFunction06()};
function myFunction06() { hexinput06.value = colorpicker06.value;}
document.getElementById("colorpicker07").onchange = function() {myFunction07()};
function myFunction07() { hexinput07.value = colorpicker07.value;}
document.getElementById("colorpicker08").onchange = function() {myFunction08()};
function myFunction08() { hexinput08.value = colorpicker08.value;}
document.getElementById("colorpicker09").onchange = function() {myFunction09()};
function myFunction09() { hexinput09.value = colorpicker09.value;}
document.getElementById("colorpicker10").onchange = function() {myFunction10()};
function myFunction10() { hexinput10.value = colorpicker10.value;}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments