Skip to content
Advertisement

I tried to make a Color Flipper in JS without tutorials and it doesn’t work

It looks logically fine(to me), but I have no idea why it doesn’t work. If someone can explain to me the logic behind why it doesn’t work I would be forever grateful.

        var i = 0;
            
        
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Ch10 JavaScript Dom</title>

<style type="text/css">
    div {position: relative}
    h1 {margin: 25px auto; width: 100%; background-color: #E84B0D; text-align: center; font-size: 24px; font-family: sans-serif; color: #FFF}
    
    #leftbutt {width: 100px}
</style>

    </head>
    <body>
        <div id='theDiv'>
            
            <h1>The HTML DOM</h1>
            <input type="button" id="button" value="Activate!">
            
            <p id="target"></p>

        </div>

    <script>
  var targetDiv = document.getElementById("theDiv");
  
        var i = 0;
   document.getElementById("button").onclick = function(){
            var arrayOfColors = 
            ["#FF5733", 
            "#7D4C42", 
            "#30944B", 
            "#307F94", 
            "#234E8F", 
            "#58238F", 
            "#8F235E", 
            "#8F2354",
            "#FF5476", 
            "#6F6B6C"];
            targetDiv.style.backgroundColor = arrayOfColors[i++];
            console.log(i);
            
        }
        
 
        if(i = 9) {
                i = 0;
                
             }

</script>
    </body>
</html>

The way I think it works(and I’m totally wrong probably) is that the i value iterates through the array of colours until it hits 9 and then the if statement changes it back to 0. But it does not work like that apparently… XD

Advertisement

Answer

You just need to update the if condition. Also, place your if condition at the start of the button click function.

document.getElementById("button").onclick = function(){
if(i == 9) {
    i = 0;       
}
var arrayOfColors = [
    "#FF5733", 
    "#7D4C42", 
    "#30944B", 
    "#307F94", 
    "#234E8F", 
    "#58238F", 
    "#8F235E", 
    "#8F2354",
    "#FF5476", 
    "#6F6B6C"
];
    targetDiv.style.backgroundColor = arrayOfColors[i++];
    console.log(i);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement