user2456977 user2456977 - 2 years ago 249
HTML Question

Change Button color onClick

I want my

to change color every time I click on it. But it only changes color on the first click.

I believe the problem is in the
function. Every time I click on the
gets set to 1. So even when I set it to 0, it gets reset to 1 on the next click. How do I fix this? Are there global variables in javascript/html where this would easily be solved?

<!DOCTYPE html>

function setColor(btn, color){
var count=1;
var property = document.getElementById(btn);
if (count == 0){ = "#FFFFFF"
else{ = "#7FFF00"



<input type="button" id="button" value = "button" style= "color:white" onclick="setColor('button', '#101010')";/>


Answer Source

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
   = "#FFFFFF"
            count = 1;        
        else {
   = "#7FFF00"
            count = 0;

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download