1

I'm trying to change the background color of a element when it is clicked on. Basically, I want to be able to toggle this color back and forth each time it's clicked.

Here's the code I'm using:

        function activateButton1() {
            var x = document.getElementById('postButton1');

            if (x.className == 'postButton1') {
                x.className = 'postButton1on';
            } else {
                x.className = 'postButton1';
            }
        }

I'm using two different CSS classes that have different background colors, but it's not working. Can anyone offer any insight?

Treedot
  • 101
  • 1
  • 10
  • Could you show a working example with your HTML too. Presumably `x.classList.toggle('postButton1on')` should solve your problem if you arrange your CSS correctly – Rory McCrossan Jan 16 '17 at 22:32
  • Possible duplicate of [How do I toggle an element's class in pure JavaScript?](http://stackoverflow.com/questions/18880890/how-do-i-toggle-an-elements-class-in-pure-javascript) and http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript will also be much helpful – Kiran Shakya Jan 17 '17 at 01:12

3 Answers3

1

This can be done with the toggle method:

function activateButton1() {
    this.classList.toggle("postButton1on");
}

You could even fire this in the html to simplify things:

<tr onclick="this.classList.toggle('postButton1on')">...</tr>

And then as long as the .postButton1on css is declared after the .postButton1 css then the .postButton1on background color will overwrite what was set previously.

Eric G
  • 2,577
  • 1
  • 14
  • 21
0

Using jQuery you can do it by

$( "#postButton1" ).on('click', function(){
  $( this ).toggleClass( "postButton1on" );
};
Clinton Green
  • 9,697
  • 21
  • 68
  • 103
0

Might not be working because you might be mixing id and class, as they have the same name, at least in the JS you posted. Here's everything packed in an HTML document, tested to work:

<!DOCTYPE html>
<html>
<head>
  <style>
    .off {
      background-color: white;
    }
    .on {
      background-color: red;
    }
  </style>
  <script>
    function change() {
      var x = document.getElementById('post');
      if (x.className.match('on')) {
        x.className = 'off';
      } else {
        x.className = 'on';
      }
    }
    function change2() {
      var x = document.getElementById('row');
      if (x.className.match('on')) {
        x.className = 'off';
      } else {
        x.className = 'on';
      }
    }
  </script>
</head>
<body>
  <button id="post" onclick="change()" class="on">hello</button>
  <table>
    <tr id="row" onclick="change2()" class="on">
      <td>hey</td>
      <td>hey</td>
    </tr>
  </table>
</body>
</html>
pithonsmear
  • 115
  • 2
  • 7