Reputation: 2762
I have a div, and I want it to exhibit the following behavior:
Instantly turn solid red; Fade out to 50% opacity over 2 seconds; Repeat when triggered by a certain event.
This is the code I have put in a callback that gets called every ~2 seconds:
currElem.style.transition = 'none';
currElem.style.opacity = 1;
currElem.style.transitionProperty = 'opacity';
currElem.style.transitionDuration = '2s';
currElem.style.opacity = 0.5;
However, this does not work. Any help?
Thanks in advance.
Upvotes: 1
Views: 542
Reputation: 99484
I'd suggest to use CSS animations instead.
Here you go:
.box {
background-color: tomato;
width: 200px;
height: 200px;
opacity: 1;
-webkit-animation: reduce_opacity 2s linear infinite;
-moz-animation: reduce_opacity 2s linear infinite;
-o-animation: reduce_opacity 2s linear infinite;
animation: reduce_opacity 2s linear infinite;
}
@-webkit-keyframes reduce_opacity { from { opacity: 1; } to { opacity: 0.5; } }
@-moz-keyframes reduce_opacity { from { opacity: 1; } to { opacity: 0.5; } }
@-o-keyframes reduce_opacity { from { opacity: 1; } to { opacity: 0.5; } }
@keyframes reduce_opacity { from { opacity: 1; } to { opacity: 0.5; } }
The infinite
keyword belongs to animation-iteration-count
property which defines the number of times an animation cycle should be played.
As you mentioned that you're triggering the repeating the animation by a JavaScript event, you can stick with transition
and remove/add a certain class within the event handler to achieve the effect:
.animate {
-webkit-transition: opacity 2s linear;
-moz-transition: opacity 2s linear;
-ms-transition: opacity 2s linear;
-o-transition: opacity 2s linear;
transition: opacity 2s linear;
opacity: 0.5;
}
JavaScript (jQuery version)
$('#reset-animation').on('click', function() {
$('.box').removeClass('animate');
setTimeout(function() {
$('.box').addClass('animate');
}, 100);
});
Upvotes: 2