Amadi
Amadi

Reputation: 23

JavaScript Eventlisteners

I am trying to change the body's background-color using JS Event-listeners. No error codes and the color isn't changing when the button is clicked.

//Change body background-color
var buttonFour = document.querySelector("#button-four");

let colorOptions = ["brown", "blue", "orange", "green", "white"];

buttonFour.addEventListener("toggle", function() {
  for(let i = 0; i < colorOptions.length; i++) {
    document.body.style.background = colorOptions[i];
  }
})

Upvotes: 0

Views: 40

Answers (2)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

Few observations :

  • Instead of listening toggle event, listen for click event.
  • Loop inside the event listener will always end up with the last element (white color).

Solution : Instead of loop we can fetch the random color from an array.

//Change body background-color
var buttonFour = document.querySelector("#button-four");

let colorOptions = ["brown", "blue", "orange", "green", "white"];

buttonFour.addEventListener("click", function() {
document.body.style.background = colorOptions[Math.floor(Math.random()*colorOptions.length)];
})
<button id="button-four">Change color</button>

OR

//Change body background-color
var buttonFour = document.querySelector("#button-four");

let colorOptions = ["brown", "blue", "orange", "green", "white"];

buttonFour.addEventListener("click", function() {
  for(let i = 0; i < colorOptions.length; i++) {
    document.body.style.background = colorOptions[i];
  }
  const poppedColor = colorOptions.pop();
  colorOptions.unshift(poppedColor);
})
<button id="button-four">Change color</button>

Upvotes: 0

Michael Horn
Michael Horn

Reputation: 4089

What you probably want to listen for is a "click" event. "toggle" is specifically fired when the state of a <detail> tag changes. https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement/toggle_event

buttonFour.addEventListener("click", function() {
  for(let i = 0; i < colorOptions.length; i++) {
    document.body.style.background = colorOptions[i];
  }
})

Edit: Just realized, there's a problem with your handler as well though - Every time you call the above handler, the background will simply cycle through all the colors instantaneously - always ending with white. You need to keep track of which color you're currently showing, and go to the next one on each click:

function colorChanger() {
  let currentColor = 0;
  return function handler() {
    currentColor = (currentColor + 1) % colorOptions.length
    document.body.style.background = colorOptions[currentColor];
  }
}

buttonFour.addEventListener("click", colorChanger())

Upvotes: 1

Related Questions