8

I wand to implement a click event in css3 transition for a div tag. I want it to be like a normal button click event. Still I couldn't find a way to do this. Please can any one help me on this.

Chathuraka
  • 395
  • 1
  • 4
  • 14

2 Answers2

6

As per CSS3 transitions:

div
{
    transition-property: width;
    transition-duration: 1s;
    transition-timing-function: linear;
    transition-delay: 2s;
}

transition-property: Specifies the name of the CSS property to which the transition is applied.

transition-duration: Defines the length of time that a transition takes. Default 0.

transition-timing-function: Describes how the speed during a transition will be calculated. Default "ease".

transition-delay: Defines when the transition will start. Default 0.

One more property to use all the rest: transition: A shorthand property for setting the four transition properties into a single property.

div
{
    transition: width 1s linear 2s;
}

Or if you want to use plain css pseudo-classes:

Given this html:

<button>Click me!</button>

Use these pseudo-classes:

button { }
button:hover { background-color: lime; }
button:active { background-color: fuchsia; }
button:focus { background-color: yellow; }

:hover is when the mouse is over the element.

:active is when the element is clicked (and hold).

:focus is when you tab to the element.

Hope it helps!

Esteban
  • 3,108
  • 3
  • 32
  • 51
5

You have two basic options:

  • Use the pseudo-class :active in your CSS. The element will then transition to the :active state when clicked (assuming an anchor). Although this isn't necessarily the best bet if you need wide browser-coverage (ie: not supported by older browsers), it is the only option for a pure-CSS implementation.

  • Use JavaScript. Using JavaScript, you can switch the element's class on-click, which will allow you to change the appearance of the element (including any transitions you have set on it). Something like:

    $('.selector').click(function(e){
        $(this).toggleClass('new-class');
        e.preventDefault();
    });
    

There is a third - very hacky - option which involves using a sibling form input (a checkbox) and inheriting off it's checked state, but it's probably not what you're looking for.

For posterity's sake, here's a Fiddle that demonstrates what I'm talking about (from a previous Stack Overflow question): http://jsfiddle.net/nMNJE/

Community
  • 1
  • 1
johnkavanagh
  • 4,614
  • 2
  • 25
  • 37