Wildbit

The Blog

Thoughts on building web apps, businesses, and virtual teams.

15 Feb Controlling CSS transition with TransitionEnd event ← Go back

Posted by Eugene Fedorenko on February 15, 2013 — 0 Comments

Recently while redesigning one of Beanstalk’s pages I had an interesting problem to solve. I had a few blocks which I wanted to highlight as a result of user’s action. The most natural way to do this is with CSS transitions and a bit of JavaScript:

.box-to-illuminate {
    background-color: yellow;
    transition: background 500ms ease;
}
.box-to-illuminate.illuminate {
    background-color: red;
}
$('.box-to-illuminate').click(function () {
    $(this).addClass('illuminate');
});

The problem is that class ‘illuminate’ would be kept on the block, so the next time a user performs an action it won’t be highlighted.

The simplest way to solve this is to add a timeout (check out Fiddle):

$('.box-to-illuminate').click(function () {
    var self = $(this),
        timeout;

    self.addClass('illuminate');

    timeout = window.setTimeout(function () {
        self.removeClass('illuminate');
    }, 500);
});

What I didn’t like about this solution is that now transition duration must be specified both in CSS and JS. This makes both of them less maintainable and more prone to errors, which is something I’m trying to avoid.

Turns out a new event called ‘transitionend’ was introduced in CSS3. It is fired at the completion of the transition and is already supported (sometimes with prefixes) by many browsers, with a notable exception of Internet Explorer 9 and below. I wasn’t really concerned about IE and gave it a try:

$('.box-to-illuminate').click(function () {
    $(this)
        .addClass('illuminate')
        .bind('webkitTransitionEnd oTransitionEnd transitionend', function () {
            $(this).removeClass('illuminate');
        }
    );
});

Works like a charm! Now transition styles are completely separated from a trigger and code is much more maintainable.

0 Comments

— No comments yet, be the first!

Sorry, comments for this entry are closed at this time.

← Go back

Get in Touch

Wildbit, LLC

Work 20 North 3rd St, 701
Philadelphia, PA 19106 USA

Google Maps
 
 
Fax
+1 (267) 200 0835
Email