Hello, I’m having some difficulty understanding events and calling functions inside addEventListener
I’m attempting to change the background color of the body of the page each time I click on the <button>
element. The background changes once and then remains red, never changing back to blue. I’m having a hard time understanding what happens when the function is complete and why it does not start over again at blue. I’ve tried the following:
var button = document.querySelector("button");
button.addEventListener("click",function(){
document.body.style.backgroundColor = "red";
document.body.style.backgroundColor = "blue";});
My first instinct was to use a for loop, however as there is only one element we’re targeting and not really looping through elements, I figured it wouldn’t be appropriate here. I also attempted to define two separate functions and run like below, again no dice.
var button = document.querySelector("button");
function red(){
document.body.style.backgroundColor = "red";
};
function blue(){
document.body.style.backgroundColor = "blue";
};
button.addEventListener("click", red);
button.addEventListener("click", blue);
Would anyone be able to help me understand what’s going on? I could easily look at code but feel this is critical to know. Thanks!