tags:

views:

696

answers:

3

Usually I would use :hover, but I want my website to be accessible on touchscreen media too.

I know I can use :active, but as soon as I let go of the mouse button, it goes back to its inactive state.

Effectively I want:

Mouse Down : Div goes green

Mouse Up: Div stays green

Mouse Down: Div goes red

Mouse Up: Div stays red

Instead of:

Mouse Down: Div goes green

Mouse Up: Div goes red

A: 

You could "toggle" a css class back and forth. So, on the first mouse down, set a class to make the div green. On every following mouse down, if the "green" class is set on the div, replace it with the "red" class, but if the "red" class is on the div, replace it with the "green" class.

This is pretty much just like the jQuery "toggle" action.

Chaulky
+1  A: 

Use jQuery.

$(function(){
    $('#yo-content').click(function() { 
        $(this).toggleClass('make-me-green');
    });
});

CSS:

#yo-content { 
    background-color: #ff0000;
    cursor: pointer;
}

.make-me-green { 
    background-color: #33ff00 !important;
}

HTML:

<div id="yo-content">Feel free to click</div>
simplemotives
Really helped, thanks.
danixd
Props come by way of selected answer, young skywalker.
dclowd9901
+1  A: 

To my knowledge, there is no pure-CSS way of achieving what you effectively want.

But jQuery could come handy there...

 // let's suppose your div's (on page load) initial state is red (#F00), 
 // and this flag will stand for it
 var initialState = true; // setup a global state flag
 $("#foo").mousedown( function() { // on mousedown
   $(this).css("background-color", intialState ? "#0F0" : "#F00"); // toggle bgColor
   initialState = !initialState; // toggle flag
 });

Instead of setting css properties, you could set/add/remove classnames if you'd like the presentational aspects to stay as CSS-centric as possible (which is a decent perspective).

Alain Saint-Etienne