Css change element style on click

I have a list of items, and I want to change the style of the item when I click on a list item (and this particular style will remain unchanged until the user clicks on another list item).

I tried using the "active" style, but did not succeed.

My code is:

#product_types { background-color: #B0B0B0; position: relative; /*overflow: hidden;*/ } #product_types a:active { background-color:yellow; } 

but this element is "yellow" only a millisecond, and I actually click on it ...

+4
source share
2 answers

Use the class pseudo-class: focus

 #product_types a:focus { background-color:yellow; } 

See this example -> http://jsfiddle.net/7RASJ/

The focus class pseudo-class works with elements such as form fields, links, etc.

+12
source

The reason it doesn't work in other browsers is due to the css focus specification. It states:

Class pseudo-class: applied when the element has focus (accepts keyboard events or other forms of text input).

Thus, it works great with text input fields or when focusing using the tab key. To make it compatible with other browsers above, add the tabindex attribute to each element, and this seems to fix the problem.

HTML:

 <ul> <li id = 'product_types'><a href='#' tabindex="1">First</a></li> <li id = 'product_types'><a href='#' tabindex="2">Second</a></li> </ul> 

CSS

 #product_types { background-color: #B0B0B0; position: relative; } #product_types a:focus { background-color:yellow; } 

JSFiddle example

+4
source

All Articles