0
User-defined functions
Why won't my defined function work on one button (redButton) but when I run the same exact code without calling it as a function, it works (blueButton & greenButton) https://code.sololearn.com/WtB1jp3e520e/?ref=app
2 ответов
+ 3
You were calling the changeColor function instead of assigning it as event handler function.
window.onload = function()
{
const changeColor = () =>
{
document.body.style.backgroundColor = event.target.style.color;
};
const createButton = (caption, colour) =>
{
let btn = document.createElement("button");
btn.appendChild(document.createTextNode(caption));
btn.style = "width: 100%; color: " + colour;
btn.addEventListener("click", changeColor);
buttonBox.appendChild(btn);
return btn;
};
const buttonBox = document.getElementById("buttons");
buttonBox.style.border = "3px solid blue";
const redButton = createButton("Red", "red");
const greenButton = createButton ("Green", "green");
const blueButton = createButton ("Blue", "blue");
}
+ 4
redButton.onclick = function changeColor() {
document.body.style.background = redButton.style.color;
};
https://code.sololearn.com/WNiBZ50XxXj8/?ref=app