How to make when the button is pressed it continues with the different color

1

Hello, I wish that when the button was pressed, it would change color and continue like this until another button is pressed. I tried with :focus , but if you press another element the color comes back.

Buttons:

<input type="button" class="button" name="button1" id="button1" value="button1">
<input type="button" class="button" name="button2" id="button2" value="button2">

CSS:

.button
{
    background: #76c764;
    height: 30px;
    width: 49%;
    border: none;
    border-radius: 5px;
}
.button:focus
{
    box-shadow: 0 0 0 0;
    border: 0 none;
    outline: 0;
    background: #69e673;
} 
    
asked by anonymous 12.03.2017 / 19:11

1 answer

1

You can do this with JavaScript or with HTML and CSS, but then with some ingenuity ...

If you do with HTML you have to change the structure a bit and it could be like this, but it's a bit of a hack.

fieldset {
	border: none;
}
button {
	border: none;
	border-radius: 5px;
	background: #eef;
	margin: 0;
	padding: 0;
}

fieldset label {
	display: block;
	padding: 10px;
	font-size: 15px;
}

fieldset input[type="radio"] {
	display: none;
}
fieldset input[type="radio"]:checked + button {
	background-color: #aaf;
}
<fieldset>
    <input type="radio" name="algo" id="um">
    <button>
        <label for="um">clica-me</label>
    </button>
</fieldset>
<fieldset>
    <input type="radio" name="algo" id="dois">
    <button>
        <label for="dois">clica-me</label>
    </button>
</fieldset>

With JavaScript it would be simpler:

var radios = document.querySelectorAll('.radio');
function toggleButton(el) {
  for (var i = 0, l = radios.length; i < l; i++) {
    var fn = radios[i] == el ? 'add' : 'remove';
    radios[i].classList[fn]('focus');
  }
}
.button {
  background: #76c764;
  height: 30px;
  width: 49%;
  border: none;
  border-radius: 5px;
}

.button.focus {
  box-shadow: 0 0 0 0;
  border: 0 none;
  outline: 0;
  background: #69e673;
}
<input type="button" class="button radio" name="button1" id="button1" value="button1" onClick="toggleButton(this);">
<input type="button" class="button radio" name="button2" id="button2" value="button2" onClick="toggleButton(this);">
    
12.03.2017 / 19:38