shmnsw
shmnsw

Reputation: 649

JavaScript setting new background-color by click

Can't change the background-color of the section below onclick, trying to figure out what's incorrect.

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.onload=function(){
                document.getElementById("top_bar").getPropertyValue("background-color").onclick=function(){
                    this="green";    
                }
            }
        </script>
    </head>
    <body>
        <section id="top_bar"></section>
    </body>
</html>

Upvotes: 0

Views: 66

Answers (2)

Julian F. Weinert
Julian F. Weinert

Reputation: 7570

document.getElementById("top_bar").addEventListener('click', function() {
    this.style.backgroundColor = "green";
}
// I like the above code better, because you don't see the `onclick` in the DOM, but this would be more like your approach:
document.getElementById("top_bar").onclick = function() {
    this.style.backgroundColor = "green";
}

Read more about the getPropertyValue function here

Upvotes: 2

csharpwinphonexaml
csharpwinphonexaml

Reputation: 3683

There's no onclick property on background-color property You must refer to the button's onclick event and then set the background-color property on the button. Here you can see how:

Replace this:

 window.onload=function(){
            document.getElementById("top_bar").getPropertyValue("background-color").onclick=function(){
                this="green";    
            }
        }

with this:

 window.onload=function(){
            document.getElementById("top_bar").onclick=function(){
                this.style.setProperty ("background-color", "green", null);
            }
        }

Upvotes: 1

Related Questions