Issue
I have a CSS animation effect that makes text blink 3 times. I want it to reset its state every time I get different response (in example below, buttons are acting as response)
How could I achieve resetting the state of CSS animation through jQuery?
(function($) {
$.fn.replaceClass = function(pFromClass, pToClass) {
return this.removeClass(pFromClass).addClass(pToClass);
};
}(jQuery));
$("#true").click(function() {
$('#animate').replaceClass('false flashit', 'true flashit');
console.log("True clicked");
});
$("#false").click(function() {
$('#animate').replaceClass('true flashit', 'false flashit');
console.log("False clicked");
});
@-webkit-keyframes flash {
0%,
to {
opacity: 1
}
}
@keyframes flash {
0%,
to {
opacity: 1
}
}
.flashit {
-webkit-animation: flash linear 1s 3;
-moz-animation: flash linear 1s 3;
animation: flash linear 1s 3
}
.true {
color: green
}
.false {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="animate">I am going to get animated!</span>
<div>
<p style="margin-bottom:5px">These buttons are acting as response</p>
<button id="true">True</button>
<button id="false">False</button>
</div>
Solution
The problem seems to be, that immediately adding the class flashit
back to the element after removing it doesnt register that the class was added again.
When adding a setTimeout
within your replace function after removing the class, it works. Notice that there is no delay specified for the timeout, so we basically just wait for the removeClass
part to finish and then immediately schedule the the execution of addClass
.
(function($) {
$.fn.replaceClass = function(pFromClass, pToClass) {
this.removeClass(pFromClass)
setTimeout(() => {
this.addClass(pToClass);
});
return this;
};
}(jQuery));
$("#true").click(function() {
$('#animate').replaceClass('false flashit', 'true flashit');
console.log("True clicked");
});
$("#false").click(function() {
$('#animate').replaceClass('true flashit', 'false flashit');
console.log("False clicked");
});
@-webkit-keyframes flash {
0%,
to {
opacity: 1
}
}
@keyframes flash {
0%,
to {
opacity: 1
}
}
.flashit {
-webkit-animation: flash linear 1s 3;
-moz-animation: flash linear 1s 3;
animation: flash linear 1s 3
}
.true {
color: green
}
.false {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="animate">I am going to get animated!</span>
<div>
<p style="margin-bottom:5px">These buttons are acting as response</p>
<button id="true">True</button>
<button id="false">False</button>
</div>
Answered By - Lapskaus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.