简体   繁体   中英

Button to change background color

I wrote this short code to display a button that changes the background color to blue. The background color changes before I even click the button, and I'm just not sure why, shouldn't the background be white by default until I click the button?

//function to change background color
function changeBg(color) {
    document.body.style.backgroundColor = color;
}

// goBlue closure
var goBlue = changeBg("blue");

// create button
var blueButton = document.createElement("button");
blueButton.innerHTML = "Blue";

// add button to page
var body = document.getElementsByTagName("body")[0];
body.appendChild(blueButton);

//add event listener
blueButton.addEventListener("click", goBlue);

Thanks for your help

That's because on line 7 you're calling the function!

var whatever = changeBg("blue") // <<<< Bam! BG is now blue
// and the value of whatever is undefined since the function is void

what you want is perhaps:

 const EL_body = document.querySelector("body"); const EL_btn = document.createElement("button"); const changeBodyBg = (color) => EL_body.style.backgroundColor = color; EL_body.append(EL_btn); EL_btn.innerHTML = "Blue"; EL_btn.addEventListener("click", () => changeBodyBg("blue"));

Above just for simplicity sake I used better function naming and a different syntax with Arrow Functions , you would have exactly this edits:

// REMOVE LINE 7 and...

blueButton.addEventListener("click", function() {
  changeBg("blue")
});

var goBlue = changeBg("blue"); will immediately invoke background color change.

Instead, try to pass changeBg to anonymous function in event listener

function changeBg(color) {
  document.body.style.backgroundColor = color;
}

// create button
var blueButton = document.createElement("button");
blueButton.innerHTML = "Blue";

// add button to page
var body = document.getElementsByTagName("body")[0];
body.appendChild(blueButton);

blueButton.addEventListener("click", () => {
  changeBg("blue")
});

This is because you've called the function changeBg and you are assigning the return value(which is undefined) of function changeBg to goBlue variable.

var goBlue = changeBg("blue");

If you want to change the color on click of a button then you need to add addEventListener .

 //function to change background color function changeBg(color) { document.body.style.backgroundColor = color; } // create button var blueButton = document.createElement("button"); blueButton.textContent = "Blue"; // add button to page var body = document.getElementsByTagName("body")[0]; body.appendChild(blueButton); //add event listener blueButton.addEventListener("click", () => { changeBg("blue"); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM