I have a list of items. The user can select an item by clicking. I want to change the color of the selected item by using CSS. Suppose the user clicked on item1, then item1 will get red color. Now if user clicks on item 2, then item2 will get red color. My HTML code:
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
Adding a tabindex to each li element allows you to apply a :focus pseudo-class:
li:focus {
color: red;
outline: none;
}
<ul>
<li tabindex=1>item1</li>
<li tabindex=1>item2</li>
<li tabindex=1>item3</li>
</ul
You can do this with just CSS by using the :focus pseudo selector:
li:focus{
color:red;
outline:none;
}
This requires the elements be focusable. Adding a tab index is probably appropriate for what you are doing and will work.
<ul>
<li tabindex="0">item1</li>
<li tabindex="0">item2</li>
<li tabindex="0">item3</li>
</ul>
here is an answer about which elements recieve focus: Which HTML elements can receive focus?
http://jsbin.com/nokiyapejo/edit?html,css,js,output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With