Change background colour on button click toggleable

Viewed 83

I'm trying to make a toggleable button with the label class "Toggle" change the background of the website on click.

My html is:

<label class="Toggle" id="Toggle-bg" onclick="Togglebg()>
<input type="Checkbox">
<span class="Slider Rounded"></span>
</label>
<p id="Toggle-p">Toggle background</p>

and I would like to add this CSS to the document when it is clicked:

.Background{background: linear-gradient(45deg,lightblue,lightgreen,yellow,orange)}

I'd like it to be toggleable but load the page untoggled, thanks!

Javascript or jquery is fine.

2 Answers

You can use a boolean variable for the toggle mechanism.

let togg = false;

document.getElementById("inp").addEventListener("click", Togglebg);

function Togglebg() {
  if (togg) {
    console.log(togg);
    document.getElementById("Toggle-p").style.background = "white";
    togg = false;
  } else {
      console.log(togg);

    togg = true;
    document.getElementById("Toggle-p").style.background = "linear-gradient(45deg, lightblue, lightgreen, yellow, orange";
  }
}
.Background {
  background: linear-gradient(45deg, lightblue, lightgreen, yellow, orange)
}
<label class="Toggle" id="Toggle-bg"> <input id="inp" type="Checkbox">
<span class="Slider Rounded"></span>
</label>
<p id="Toggle-p">Toggle background</p>

you only need to use classList.toggle at your element target. you can create your function passing a target element to be reusable:

function Togglebg(target) {
  target.classList.toggle('Background')
}

and remove onclick="Togglebg() from your label element. Attach the label's click eventListener at your javascript file.

below a snippet implementation:

function Togglebg(target) {
  target.classList.toggle('Background')
}

const toggler = document.querySelector('#Toggle-bg')

toggler.addEventListener('click', () => Togglebg(document.querySelector('body')))
.Background{background: linear-gradient(45deg,lightblue,lightgreen,yellow,orange)}
<label class="Toggle" id="Toggle-bg">
<input type="Checkbox">
<span class="Slider Rounded"></span>
</label>
<p id="Toggle-p">Toggle background</p>

Related