Reputation: 5992
I am trying to animate opacity( and translate value ) from 0 to 1 and than back to 0, when the class is removed. The opacity animates nicely to 1, but it does not animate back to 0. Instead it just jumps. See this pen to see my problem in action. What am I missing here?
https://codepen.io/timsim/pen/QvppGz
Code:
.cp-active {
transform: translateY(50px) !important;
opacity: 1 !important;
}
#cp {
background-color:red;
top: -30px;
position: relative;
width: 85%;
margin: auto;
box-shadow: none;
border-color: black;
z-index: 1;
opacity: 0;
-webkit-transition: -webkit-transform 0.5s ease-in-out;
height:100px;
width:100px;
}
$("body").on("click", function(){
if ($("#cp").hasClass("cp-active")){
$("#cp").removeClass("cp-active")
}else{
$("#cp").addClass("cp-active")
}
});
Upvotes: 1
Views: 1198
Reputation: 1586
Hey check out this fiddle. Your transition need to be on ALL and not only on TRANSFORM This:
transition: all 0.5s ease-in-out;
instead of:
transition: transform 0.5s ease-in-out
because you are animating opacity as well.
Also i switched your jQuery fnction. It's simpler now
$("body").on("click", function() {
$("#cp").toggleClass("cp-active");
});
#cp.cp-active {
transform: translateY(50px);
opacity: 1;
}
#cp {
background-color: red;
position: relative;
width: 85%;
margin: auto;
box-shadow: none;
border-color: black;
opacity: 0;
-webkit-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
transform: translateY(0px);
height: 100px;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cp">Hello</div>
Upvotes: 4
Reputation: 17687
Traver solution above is very good. here's another one using just JQ ( without any other css except general #cp styles )
$("body").on("click", function(){
if ($("#cp").hasClass("isVisible")){
$("#cp").animate({
'top':'-50',
"opacity":"0"
},500).removeClass("isVisible")
}else{
$("#cp").animate({
'top':'0',
"opacity":"1"
},500).addClass("isVisible")
}
});
body {
height:100vh;
}
#cp {
background-color:red;
position: relative;
top:-50px;
width: 85%;
margin: auto;
box-shadow: none;
border-color: black;
z-index: 1;
-webkit-transition: -webkit-transform 0.5s ease-in-out;
opacity:0;
height:100px;
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cp"></div>
Upvotes: 0