Home > Back-end >  Change thebackground color of the body on click with JS
Change thebackground color of the body on click with JS

Time:11-11

I want to change the bg of the body when the user clicks on a button (Click here to change the color of the background of the body) on the top of the page; here is the page:https://relaxed-ardinghelli-701d99.netlify.app/ I managed to do it only once; I used the for loop so the same code gets executed 10 or 20 times.. but it is not working:

for(let i=0; i<100; i  ){
bg_button.addEventListener("click", funct2);
function funct2(e) {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
bg_button.addEventListener("click", funct3);

function funct3(e) {
    body.style.backgroundColor = "white"
    section_top.style.backgroundColor=""}}}

CodePudding user response:

If you want change background color on button click, you should use JavaScript function and change a style in the HTML page.

function chBackcolor(color) {
   document.body.style.background = color;
}

It is a function in JavaScript for change color, and you will be call this function in your event, for example :

<input type="button" onclick="chBackcolor('red');">

If you want it only for some seconds, you can use setTimeout function:

window.setTimeout("chBackColor()",10000);

CodePudding user response:

If you want the button to toggle the background color no matter how many times you click it, you can do it in a single event listener that updates a state variable:

let toggleState = false

function toggleBackground() {
  toggleState = !toggleState
  if (toggleState) {
    body.style.backgroundColor = "lightgrey"
    section_top.style.backgroundColor="white"
  } else {
    body.style.backgroundColor = "white"
    section_top.style.backgroundColor=""
  }
}

bg_button.addEventListener("click", toggleBackground);

Or you can replace the event listener instead of adding a new one on click:

function setBg1() {
  body.style.backgroundColor = "lightgrey"
  section_top.style.backgroundColor="white"
  bg_button.onclick = setBg2
}

function setBg2() {
  body.style.backgroundColor = "white"
  section_top.style.backgroundColor=""
  bg_button.onclick = setBg1
}

bg_button.onclick = setBg1

CodePudding user response:

Hi you an use the following function:

function bgColorToggle () {
   const availableColors = ['blue','red'];
   for(int i=0;i<100;i  ) {
     let color = availableColors[i%2];
     setTimeout((document.body.style.color = color),2000);
   }
}
  • Related