Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS fadein fadeout onclick

Tags:

html

jquery

css

I am trying to use CSS animations on a div which is shown/hidden using toggle().

I have added ease-in-out on my animation but it only fades in and will not fade out.

Here is my css:

#form {
display: none;
animation: formFade 2s ease-in-out;
-moz-animation: formFade 2s ease-in-out; /* Firefox */
-webkit-animation: formFade 2s ease-in-out; /* Safari and Chrome */
-o-animation: formFade 2s ease-in-out; /* Opera */
}

@keyframes formFade {
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-moz-keyframes formFade { /* Firefox */
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-webkit-keyframes formFade { /* Safari and Chrome */
from {
    opacity:0;
}
to {
    opacity:1;
}
}
@-o-keyframes formFade { /* Opera */
from {
    opacity:0;
}
to {
    opacity: 1;
}
}

Here is the html/js:

<form id="form" >
TEST
</form>

<script>
            $('#formButton').on('click', function() {
            $("#form").toggle();

            });
        </script>  

It fades in onclick but doesn't fade out. Any ideas why?

like image 940
ServerSideSkittles Avatar asked Feb 10 '23 22:02

ServerSideSkittles


1 Answers

Using .toggle() to hide an element just sets it to display: none without affecting the opacity. Try this:

$('#formButton').on('click', function() {
    if ($('#form').css('opacity') == 0) $('#form').css('opacity', 1);
    else $('#form').css('opacity', 0);
});
#form {
    opacity: 0;
    -webkit-transition: all 2s ease-in-out;
    -moz-transition: all 2s ease-in-out;
    -ms-transition: all 2s ease-in-out;
    -o-transition: all 2s ease-in-out;
    transition: all 2s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="form">Test</div>

<a href="#" id="formButton">Click</a>
like image 122
AlliterativeAlice Avatar answered Feb 12 '23 12:02

AlliterativeAlice