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

Asked

Viewed 1,603 times

1

Hi, I’d like when you hit the button, it would change color and continue like this until another one is pressed. I tried with the :focus, but if press another element the color 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;
} 

1 answer

1


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

If you do it with HTML you have to change the structure a little bit and it could be like this, but it’s like "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);">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.