Search code examples
functioncolorsalternate

alternate colors onClick


I am working on a javascript function that will cause the background color of a div element to alternate between lavenderblush and cyan every time the button is pressed.

When I press the button once, it will change colors, but will not change back when pressed a second time. How do I fix this?


Solution

  • Presumably, background colour can be one of 3 values, "cyan", "lavenderblush", anything else

    Now, if the logic is

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  lavenderblush
    

    Then the code should be

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "lavenderblush") {
        style.backgroundColor = "cyan";
    } else {
        style.backgroundColor = "lavenderblush";
    }
    

    Or, if the logic is

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  cyan
    

    Then the code is

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "cyan") {
        style.backgroundColor = "lavenderblush";
    } else {
        style.backgroundColor = "cyan";
    }
    

    However, if the logic is

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  *do not change*
    

    Then the code is

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "cyan") {
        style.backgroundColor = "lavenderblush";
    } else if (style.backgroundColor === "lavenderblush") {
        style.backgroundColor = "cyan";
    }
    

    Here's the first "logic" as a runnable snippet

    function Replace() {
        var style = document.getElementById('new').style;
        if (style.backgroundColor === "lavenderblush") {
            style.backgroundColor = "cyan";
        } else {
            style.backgroundColor = "lavenderblush";
        }
    }
    document.getElementById('Replace').addEventListener('click', Replace);
    <button id="Replace">Click</button>
    <div id="new">NEW</div>