.test { height:50px; width:50px; background:#000; } 
 <div class="test"></div> 

How to make it so that when you click on the block "test", it becomes red, with one more click - back to black.

    3 answers 3

    Can be done on html + css

     .test { height: 50px; width: 50px; background-color: black; } input { display: none; } input:checked + label > div { background-color: red; } 
     <input type="checkbox" id="colorbox"> <label for="colorbox"> <div class="test"></div> </label> 

      You can use the sibling selector ~ and the <label> link with <input> .

      Pros : javascript is not needed.
      Cons : need additional markup.

       .hidden { display: none; } .test { display: block; height: 50px; width: 50px; background: #000; } #switcher:checked ~ .test { background: #f00; } 
       <input type="checkbox" class="hidden" id="switcher"> <label class="test" for="switcher"></label> 

      • Fast what. ) - Andrey Fedorov

      Using javascript and jQuery:

       $('.test').on('click', function(){ $(this).toggleClass('red'); }); 

      and add to css

       .test.red{ color: red; }