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/
To make the transition occur, you must specify at least two things — the name of the CSS property to which you want to apply the transition effect using the transition-property CSS property, and the duration of the transition effect (greater than 0) using the transition-duration CSS property.
If you want to use the "highlightme" class to highlight your text, you can create a <span> tag in your HTML which references the CSS class.
Transitioning two or more properties You can transition two (or more) CSS properties by separating them with a comma in your transition or transition-property property. You can do the same with duration, timing-functions and delays as well. If the values are the same, you only need to specify one of them.
I was able to get this to work with css3 animation. Just apply the highlight
class to new elements:
$('#add-element').click(function() { $('<div class="highlight">new element</div>').appendTo('#content'); });
@keyframes yellow-fade { 0% { background: yellow; } 100% { background: none; } } .highlight { animation: yellow-fade 2s ease-in 1; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="add-element">Add element</button> <div id="content"></div>
I tested in IE 10, Chrome, Safari, and latest FF and it works there. Probably won't work in IE 9 and below...
https://jsfiddle.net/nprather/WKSrV/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With