Search code examples
javascripthtmlcssclickonload

Changing background color animation not working


I am trying to make the background color of the body change every second using the button. I need the background to change on the click of the button for other reasons (I cannot use a normal interval, timeout, or @keyframes). I can not figure out what is wrong with my code. Any ideas?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stack Overflow</title>
</head>
<body>
    <button id="click_me">Loaded</button>

    <script type="text/javascript" defer>

        const btn = document.getElementById("click_me");
        const body = document.querySelector("body");
        
        btn.onclick = () => {
            if(body.style.backgroundColor == "white"){
                body.style.backgroundColor = "black";
            } else if(body.style.backgroundColor == "black"){
                body.style.backgroundColor = "white";
            }
        }

        setTimeout(()=>{
            btn.click();
        },1000);
    </script>
</body>
</html>

Solution

  • So looks like the defautl background color for the body is really "transparent". So when you check for the white value its never found. So you just need too add an OR statment to check for the transparent value.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Stack Overflow</title>
    </head>
    <body>
        <button id="click_me">Loaded</button>
    
        <script type="text/javascript" defer>
    
            const btn = document.getElementById("click_me");
            const body = document.querySelector("body");
    
            // debug stuff
            console.log(`Here is the default value of your body color:`)
            console.log(body.style.backgroundColor)
            
            btn.onclick = () => {
                if(body.style.backgroundColor == "white" || body.style.backgroundColor == ""){
                    body.style.backgroundColor = "black";
                } else if(body.style.backgroundColor == "black"){
                    body.style.backgroundColor = "white";
                }
            }
    
            setTimeout(()=>{
                btn.click();
            },1000);
        </script>
    </body>
    </html>

    If you don't want to do this you could just always set the body color to white on load. But you really probably should be using some type of reset Reset CSS. This way you know values like this are the same across all browser instead of finding out later what went wrong. Never know, maybe the default value of the background color could change in the future to something else.