Hello everyone!
Pls check 2 methods I used to solve Task 3 of the “Test your skills” Events lesson and share your opinion as to which it the most rational one. Both ways works fine, though 2nd one seems to be rather extraordinary imho.
Thx in advance
Option A
const btns = document.querySelectorAll(“button”);
let switchColor = function () {
buttonBar.style.backgroundColor = this.dataset.color;
};
let colorChange = function (btn) {
btn.addEventListener(“click”, switchColor);
};
btns.forEach(colorChange);
Option B
const btnRed = document.getElementsByTagName(“button”)[0];
const btnYell = document.getElementsByTagName(“button”)[1];
const btnGrn = document.getElementsByTagName(“button”)[2];
const btnPurp = document.getElementsByTagName(“button”)[3];
const redColor = function () {
buttonBar.style.backgroundColor = btnRed.dataset.color;
btnRed.onclick = redColor;
};
const yellowColor = function () {
buttonBar.style.backgroundColor = btnYell.dataset.color;
btnYell.onclick = yellowColor;
};
const greenColor = function () {
buttonBar.style.backgroundColor = btnGrn.dataset.color;
btnGrn.onclick = greenColor;
};
const purpleColor = function () {
buttonBar.style.backgroundColor = btnPurp.dataset.color;
btnPurp.onclick = purpleColor;
};
redColor();
yellowColor();
greenColor();
purpleColor();
buttonBar.style.backgroundColor = “white”;*