Reputation: 101
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?
Upvotes: 1
Views: 1579
Reputation: 115
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>
Upvotes: 0
Reputation: 9977
Using jQuery you can do it by
$( "#postButton1" ).on('click', function(){
$( this ).toggleClass( "postButton1on" );
};
Upvotes: 0
Reputation: 2617
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.
Upvotes: 1