I'm trying to coding a site where I need to change the background with a button, but I can't...
I created a button that changes the color of the background while clicking a button but after I added an image as a background, it doesn't want to change the color background (obviously)...
<head>
<style>
:root{
--main-bg: url(https://www.the url of my bg.jpg);
// creating a variable for the bg of my site
}
</style>
<style>
body {
background: var(--main-bg) repeat-x;
// using this variable
}
</style>
<script>
var colors = ["#2d2d2d", "#f2f2f2"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("body");
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
// the js script to change the bg color
}
</script>
<script>
function backgroundHiding() {
let root = document.documentElement;
root.addEventListener("onclick", e => {
if (--main-bg) = "#2d2d2d" {
root.style.setProperty('--main-bg', " url(https://www.the urlof my bg.jpg)")
} else {
root.style.setProperty('--main-bg', "#2d2d2d")
}
// the js script to hide my img bg
}
</script>
<div class="button">
<body id='body'>
<button onclick="changeColor(); backgroundHiding();" class="lightbutton"><span>Turn On/Off the lights</span> </button>
// creating the button that interact with the two js functions
</div>
</head>
I expected that it works but... huh... no It works sometimes, like 1 time every 100 times, I don't know why... If someone could help me, I would really appreciate it!
Aucun commentaire:
Enregistrer un commentaire