Ewald Bos Ewald Bos - 7 months ago 20
Javascript Question

reload a javascript after CSS3 Animation is finished

i am working on a CSS3 animation that is controlled by a javascript action, so far the script works BUT only once. I can't seem to get to reload the script so it starts again at its default position:

This is the javascript:

function searchBox() {
var searchstring = document.getElementById('search').value;
var target = document.getElementById('SearchResult');

if (searchstring.length > 0) {
$("#SearchResult").addClass("animation");

} else {

if (searchstring.length == 0) {
$("#SearchResult").addClass("animation_back");
}
}
}


So it's connected from a
<input>
text field to the CSS that simply has an opacity change on a DIV, the problem is that is only work once. When I type the text in the box it changes the opacity of the DIV and when I remove the text it hides (opacity 0.0) the DIV again. But when I type again, nothing happens. Must be something small. Still learning. I tried a "return searchbox()" but that did not work. Thanks in advance for your help.

here is the css:

@keyframes SearchResult {
from { opacity: 0; }
to { opacity: 1; }
}
.animation_SearchResult{
animation-name: SearchResult;
animation-duration: 1s;
animation-timing-function: ease-out;
animation-fill-mode: forwards;
}
@keyframes SearchResult_back {
from { opacity: 1; }
to { opacity: 0; }
}
.animation_SearchResult_back{
animation-name: SearchResult_back;
animation-duration: 1s;
animation-timing-function: ease-out;
animation-fill-mode: forwards;
}


and here is the HTML

<input class="searchbox" type="text" id="search" onkeyup="searchBox()">
<div class="searchresultcontainer" id="SearchResult"></div>


the search result container at this point just hold a red background so

#SearchResult{
background-color: red;
}


Changing the function to this actually worked (thank you GMchris):

function searchBox() {
var searchstring = document.getElementById('search').value;
var target = document.getElementById('SearchResult');

if (searchstring.length > 0) {
$("#SearchResult").removeClass("animation_back").addClass("animation");

} else {

if (searchstring.length == 0) {
$("#SearchResult").removeClass("animation").addClass("animation_back");
}
}
}

Answer

You need to write.

$("#SearchResult").removeClass('animation').addClass("animation");

CSS animations are executed as soon as an element with a fitting selector is present. This means that when the animation class is added, it will trigger the animation and play it till its end, however since addClass only adds the class, and calling it again will not really do something if the class is already present, you'll need to remove the class and then add it again.