I was curious about how I could make a normal button, with a "selected" style or animation.
<button> I'm a button </button>
When you use Radiobuttons, you can see clearly that you have a selected style whenever you click on the button.
<input type="radio">
Now is the question, is it possible to have a selected style or animation (Not a click/hover animation) for the last button that you clicked (Without obviously having to use radiobuttons/checkbox).
If so, how does one make this?
JSFiddle if you want to use the code that I used in the GIF
I haven't found a lot of articles about this, or maybe just haven't looked good enough, anyways, maybe you people know how to do this?
CodePudding user response:
Just toggle a class with an onclick event:
btnState = false;
btn.addEventListener("click", () => {
btn.classList.toggle("selected");
btnState = !btnState;
});
In the CSS add:
.selected {
background-color: red;
}
And add an id="btn" to the button in the HTML.
CodePudding user response:
Include the JS in your page.
In your HTML, similarly to what you would do by adding the
name
andvalue
attributes to your<input type="radio">
s you add thedata-name
anddata-value
attributes to the elements you wish to behave as<input type="radio">
s. If you want one to be selected by default add the attribute/valuedata-selected="true"
to it.Target the selected elements in CSS with the
[data-radio-selected='true']
selector.
document.addEventListener('DOMContentLoaded', () => {
const radioGroups = {}
document.querySelectorAll('[data-radio-name]').forEach( el => {
const name = el.dataset.radioName;
const value = el.dataset.radioValue;
const selected = el.dataset.radioSelected === 'true';
// Register radio
radioGroups[name] = radioGroups[name] || {
radios: [],
selected: null
};
radioGroups[name].radios.push(el);
if ( selected && radioGroups[name].selected == null ) {
radioGroups[name].selected = value;
}
// attach listeners
el.addEventListener('click', () => {
radioGroups[name].radios.forEach( el => {
el.dataset.radioSelected = 'false';
})
el.dataset.radioSelected = 'true';
radioGroups[name].selected = value;
})
})
})
[data-radio-selected='true'] {
background: red;
}
<button data-radio-name="animals" data-radio-value="pig">
Pig
</button>
<button data-radio-name="animals" data-radio-value="cow">
Cow
</button>
<button data-radio-name="animals" data-radio-value="chicken">
Chicken
</button>