Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a button's background color when it's clicked [duplicate]

I'm trying to change the background-color property of a button using JavaScript. The script checks what the current background-color is set to and then toggles it. This is the JavaScript code:

function btnColor(btn,color) {
    var property=document.getElementById(btn);
    if (property.style.background-color == "#f47121") {
        property.style.background-color=Color;
    }
    else {
        property.style.background-color = "#f47121";
    }
}

and this is what I pass in html:

<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','#fff200');" />

toggleLayer is another function I am using, which works perfectly fine. I can't seem to figure out why it doesn't work.

like image 802
ayush Avatar asked Jun 06 '13 15:06

ayush


2 Answers

Why not just use jQuery?

Core Javascript is so raw! If you're just changing the background-color then use the on click event in jQuery:

$('#btnHousing').click(function() {
    //Now just reference this button and change CSS
    $(this).css('background-color','#f47121');
});

Personally for me it reads so much better then raw javascript.

Regards

like image 163
Tez Wingfield Avatar answered Sep 30 '22 06:09

Tez Wingfield


I made a working example in JsBin : LINK HERE

  • I renammed the function to setColor
  • I changed the property property.style.background-color by window.getComputedStyle(property).backgroundColor
like image 39
Marc-André Bilodeau-Lamontagne Avatar answered Sep 30 '22 07:09

Marc-André Bilodeau-Lamontagne