2

Could anyone tell me why changing colour after performing onclick doesn't work here ?

function butt(color) {
    if(document.getElementById("bt").style.backgroundColor=="green"){
            document.getElementById("bt").style.backgroundColor="purple";
    }
};
document.getElementById("bt").addEventListener("click", function() {
    butt("green")
});
#bt {
    background-color:yellow;
    border-radius:10%;
    padding:10px;
    margin:20px;
}            
<div class="row">
    <div id="forbutton">
        <button type="button" id="bt">It's me MrButton !</button>
    </div>
</div>

9
  • 1
    A working Stack Snippet would be useful. Commented Mar 28, 2017 at 14:44
  • 1
    how yellow == green ? make any sense? Commented Mar 28, 2017 at 14:45
  • 2
    Also, your click won't do anything as it takes style.backgroundColor from the inline style so it would ignore anything you add to your css file as it is not inline (you need to use something like element.getComputedStyle) - and as Sagar says you have used yellow but compared against green. One final thing would be why are you passing a variable into the function but not using it? Commented Mar 28, 2017 at 14:51
  • 2
    sorry that should be window.getComputedStyle(element).backgroundColour - but it will return an rgb colour rather than red or blue Commented Mar 28, 2017 at 14:59
  • 1
    @Pete @ freginold Thanks guys I'm Newbie to programming. I didn't know it treats css including in separate file as inline-style and thanks for .getComputedStyle trick. Commented Mar 28, 2017 at 15:09

1 Answer 1

1

You are just passing the string "green" through the function. Details commented in Snippet.

SNIPPET

// pass the string through function
function butt(color) {

  // If string is "green"...
  if (color === "green") {

    // Reference #bt and change it's backgroundColor to purple
    document.getElementById("bt").style.backgroundColor = "purple";
  }

};

// Register #bt to click event, when clicked...
document.getElementById("bt").addEventListener("click", function() {

  // Call butt() function passing the string "green"
  butt("green")
});
#bt {
  background-color: yellow;
  border-radius: 10%;
  padding: 10px;
  margin: 20px;
}
<div class="row">
  <div id="forbutton">
    <button id="bt">It's me MrButton !</button>
  </div>

Sign up to request clarification or add additional context in comments.

1 Comment

Secondary point, it's possible the DOM isn't loading as well, so a readyState check wouldn't hurt. Otherwise, it will fail at trying to get the document element (null value otherwise)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.