I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state: background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}
I would use a CSS class:
And change your function to:
Or if you want to use only JavaScript
Update(See comments: if you use 2 buttons):
You could do something really quick like this:
First, add a hidden input element to your page like so:
Next, put this in your highlight function:
That should work, although I agree with a previous answer that you should use a css class for this.
@Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
Also noticed that his answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.