0

I want to change the background color of a class by clicking on a class. The code that I tried doesn't work. Thank you in advance

HTML:

<a href="#!" onclick="message()" onclick="message()" class="changeBack"> SEND ME A MESSAGE </a>

CSS:

.changeBack {
    background-color: rgba(0, 0, 0, 0.0);
}

JAVASCRIPT:

function message() {

        var background = document.getElementsByClassName("changeBack").style.backgroundColor;
            if (background == "rgba(0, 0, 0, 0.0)") {
                 background = "rgba(0, 0, 0, 0.1)";
        } else {
        background = "rgba(0, 0, 0, 0.0)";
    }

}
Soccerlife
  • 671
  • 3
  • 9
  • 20

1 Answers1

3

There is your code.

function myFunction() {
    var x = document.getElementById('box');
    if (x.style.backgroundColor === 'red') {
        x.style.backgroundColor = 'blue';
    } else {
        x.style.backgroundColor = 'red';
    }
}
#box{
background-color:red;
padding:1rem;
width : 50%;
height:150px;
margin:auto;
}
<div id="box" onclick="myFunction()">
</div>
Nadim
  • 280
  • 2
  • 12
  • It doesn't work in my file. I already another onclick-function (see edit), or is this not possible? And it has to contain a if/else-statement because it's changing everytime you click on the class. edit: I deleted the message() and then it does work, but if I combine them together, it doesn''t. – Soccerlife Feb 23 '17 at 22:52
  • It does work now thank you! – Soccerlife Feb 23 '17 at 23:00
  • I edit my snippet to be toggle script you can run it now it's changing everytime. – Nadim Feb 23 '17 at 23:04