Skip to content Skip to sidebar Skip to footer

Javascript Button Style Change On Click

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 o

Solution 1:

I would use a CSS class:

.opacityClicked{
  background:rgba(255,0,0,0.8);
}
.opacityDefault{
  background:rgba(255,0,0,0.6);
}

And change your function to:

functionhighlight(id) {
    var element = document.getElementById(id);
    element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}

Or if you want to use only JavaScript

var isClicked = false;
functionhighlight(id) {
    isClicked = !isClicked;
    var element = document.getElementById(id);
    element.style.background = (isClicked  == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}

Update(See comments: if you use 2 buttons):

var buttonClicked = null;
functionhighlight(id) {
    if(buttonClicked != null)
    {
        buttonClicked.style.background = "rgba(255,0,0,0.8)";
    }

    buttonClicked  = document.getElementById(id);
    buttonClicked.style.background =  "rgba(255,0,0,0.6)";
}

Solution 2:

You could do something really quick like this:

First, add a hidden input element to your page like so:

<inputtype="button"id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />

<inputtype="hidden"id="one_neg_one" value="1" />  <= hidden element

Next, put this in your highlight function:

functionhighlight(id) {
    var a = 7;
    var o = document.getElementById("one_neg_one");
    var newa = (a + (parseInt(o.value) * -1)) * 0.1;
    document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
    o.value = o.value * -1;
}

That should work, although I agree with a previous answer that you should use a css class for this.

Solution 3:

@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:

functionhighlight(id) {
   var element = document.getElementById(id);
   element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}

Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

Post a Comment for "Javascript Button Style Change On Click"