Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css change style of an element on click

I have a list of elements, and i want to change a style of an element when one clicks on the list element(and that specific style to stay the same until the user presses another list item).

I tried using the 'active' style, but no success.

My code:

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


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

but the element is 'yellow' only a millisecond, while i actually click on it...

like image 988
dana Avatar asked May 23 '11 10:05

dana


People also ask

How do I change the color of text when clicked in CSS?

The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.

How do I change the color of a clicked button in CSS?

To change the button color on click in CSS, the “:active” pseudo-class can be used. More specifically, it can represent the button element when it gets activated. Using this class, you can set different button colors when the mouse clicks on it.


2 Answers

Use the :focus pseudo class

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

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

The focus pseudo class works on elements like form fields, links etc.

like image 82
Sparky Avatar answered Oct 28 '22 18:10

Sparky


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

The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

So it seems to work perfectly fine with text input fields or when you focus using the tab key. To make the above compatible with other browsers add the tabindex attribute to each element and this appears 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

like image 33
Biped Avatar answered Oct 28 '22 18:10

Biped