Reputation: 889
I got a Section named "login" and a Section named "register". When the opacity of them changes, I want to have a linear transition that take 0.3 seconds.
CSS:
#login{
opacity: 0;
transition:opacity 0.3s linear;}
#register{
opacity: 0;
display: none;
transition:opacity 0.3s linear;}
When you go on the Homepage HERE and click on "Query",
the opacity of #login
changes to 1. That works fine with the transition!
When you click "oder registriere dich neu" below the Login-Form,
the Login-Section gets opacity: 0
again - then get display: none
.
That also works perfect with a transition.
BUT than the REGISTER-Section is put to display: block
and then opacity: 1
(after a setTimeout
of 500 Milli-seconds.)
This don't have a transition! why?
When i click "Hast du schon einen Account?" again (to get back to the login),
the register Block will fade out with a transition perfecty again, and the login-form comes up without a transition again?
Here's the Javascript code for setting the opacities:
function changeSection(IDOut, IDIn)
{
var IDOut = "#" + IDOut;
var IDIn = "#" + IDIn;
hideSection(IDOut);
showSection(IDIn);
}
function hideSection(IDOut)
{
$(IDOut).css({opacity: "0"});
setTimeout(function(){
$(IDOut).css({display: "none"});
},500);
}
function showSection(IDIn)
{
setTimeout(function(){
$(IDIn).css({display: "block"});
$(IDIn).css({opacity: "1"});
},500);
}
IDOut is the Section, I want to Fade out (witch works perfect for login and register).
IDIn is the Section, I want to Fade in (witch DON'T WOKR for login and register)!
Why does the transition not work for IDIn? Any Ideas?
Upvotes: 0
Views: 154
Reputation: 6315
The transition does not work according to your code.
The IDIn originally has the display
property as none
and opacity
as 0
.
According to the function showSection
, you first wait for 500ms, and then set the display
and opacity
property simultaneously to what you want. Concurrency is the problem, because display and opacity are changed in one animation frame at the same time, but the browser has to choose one property to transit. And it choose display
.
More technically, transition only works on elements that are visible and have dimension. The width and height must not be zero. So display:none;
cancels out your transition.
So the solution is easy, just put display
outside of your setTimeout
. Make display
changed first.
The benefit over native jQuery method fadeIn
is that it utilizes css transition, which is more efficient than jQuery's underlying animation.
function showSection(IDIn)
{
$(IDIn).css({display: "block"});
setTimeout(function(){
$(IDIn).css({opacity: "1"});
},500);
}
Upvotes: 1
Reputation: 4584
You are using jQuery, you can do this alot simpler and let the jQuery handle it for you.
instead of your code for showSection and hideSection, use:
$('#yourselector').fadeIn(300);
to fade an element in with a time of 300 miliseconds, and:
$('#yourselector').fadeOut(300);
to hide it.
Upvotes: 2