CSS3 Transition to highlight new elements created in JQuery

Paulaner picture Paulaner · Oct 10, 2012 · Viewed 17.1k times · Source

I want to use a CSS3 color transition to apply a highlight-fading color effect (yellow to transparent) to new elements appended to the markup using JQuery.

CSS

#content div {
    background-color:transparent;
    -moz-transition:background-color 2s;
    -webkit-transition:background-color 2s;
    -o-transition:background-color 2s;
    transition:background-color 2s;
}

#content div.new {
    background-color:yellow;
}

HTML

<div id="content"></div>
<a id="add-element" href="#">add new element</a>

JS

$('#add-element').click(function() {
    var newElement = $('<div class="new">new element</div>');
    $('#content').append(newElement);
    newElement.removeClass('new');
});

When I click the link, the new element is created. Its class is "new" (background color yellow) and it's appended to the HTML markup. I should be able to immediately remove the "new" class to trigger the background color transition to transparent (or whatever other color). I'm obviously doing it wrong, since the background color of the new element is immediately shown as transparent, with no transition effect. I know I can do this in JQuery UI, but I'd like to use CSS3 transitions.

jsfiddle here:

http://jsfiddle.net/paulaner/fvv5q/

Answer

Nathan Prather picture Nathan Prather · Jun 1, 2013

I was able to get this to work with css3 animation:

@-webkit-keyframes yellow-fade {   
   0% {background: yellow;}
   100% {background: none;}
}

@keyframes yellow-fade {
   0% {background: yellow;}
   100% {background: none;}
}

.highlight {
   -webkit-animation: yellow-fade 2s ease-in 1;
   animation: yellow-fade 2s ease-in 1;
}

Just apply the highlight class to new elements:

$('#add-element').click(function() {

    var newElement = $('<div class="highlight">new element</div>');

    $('#content').append(newElement);

});

I tested in IE 10, Chrome, Safari, and latest FF and it works there. Probably won't work in IE 9 and below...

http://jsfiddle.net/nprather/WKSrV/3/

I got this method from this book in Safari Books Online: http://my.safaribooksonline.com/9780132366847/ch05lev1sec2?link=f1184788-851e-4eb6-bb0b-61cb0fb7756d&cid=shareLink