samedi 3 octobre 2015

JavaScript if statement to change Div

i am hoping to get help with my IF statement in javascript.

This is what i am trying to do. When the next button is clicked, the following should happen

If the background colour of the light div is #ff0000 (red), it should change to

ffff00 (amber)

If the background colour of the light div is #ffff00 (amber), it should change to

00ff00 (green)

If the background colour of the light div is #00ff00 (green), it should change to

ff0000 (red)

HTML

    <h1>Traffic Light</h1>

        <div class="light">


        </div>

            </br>

        <button id="next" onClick="setBgColour" type="button">Next</button>     

</div>

css

.light 
    {
        background-color: #ff0000;
        width: 100px;
        height: 20px;
        margin-left: auto;
        margin-right: auto;
    }

JavaScipt

function setBgColour(){

    if(document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000')
    {
        document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
    }

    else if (document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00')
    {
        document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00';
    }

    else

    document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000';

}

window.onload = function(){

    document.getElementById('next').addEventListener('click', setBgColour);

};

I would like some help please if i can. Feel free to give hints, edit the code.

Thank you

Aucun commentaire:

Enregistrer un commentaire