Akshay
Akshay

Reputation: 14348

Changing :active style at each click

I am trying to make a button as shown here http://jsfiddle.net/9epgs999/ Code

button:active{
background-color:yellow;
}

At :active state the button changes its background color from green to yellow. What i am trying to do is to change the background-color to blue when it is at :active state on second time (second click) and at the third click some other color is there a way to do this using css only

Upvotes: 1

Views: 107

Answers (1)

dfsq
dfsq

Reputation: 193261

Here is my idea. As you see it's pretty verbose, but you can technically make it work with only CSS:

HTML:

<div class="btn-wrap">
    <input type="checkbox" class="check yellow" />
    <input type="checkbox" class="check blue" />
    <input type="checkbox" class="check red" />
    <button>Button</button>
</div>

CSS:

.btn-wrap {
    position: relative;
    display: inline-block;
}
.btn-wrap .check {
    position: absolute;
    z-index: 10;
    width: 100%;
    height: 100%;
    opacity: 0;
}
.btn-wrap .check:checked {
    z-index: -1;
}

.btn-wrap button {
    width:100px;
    height:50px;
    background-color:green;
}

.btn-wrap .red:active ~ button {
    background-color: white;
}
.btn-wrap .red:checked ~ button:active {
    background-color: red;
}

.btn-wrap .blue:active ~ button {
    background-color: red;
}
.btn-wrap .blue:checked ~ button:active {
    background-color: blue;
}

.btn-wrap .yellow:active ~ button {
    background-color: blue;
}
.btn-wrap .yellow:checked ~ button:active {
    background-color: yellow;
}

Demo: http://jsfiddle.net/9epgs999/3/

The idea is pretty simple. There are not many options how to store state in CSS. One of them is using checkboxe's :checked pseudo class with sibling selectors.

Even though it can be done in CSS, however I would better go with just a few lines of javascript code.

Upvotes: 3

Related Questions