I have written a small amount of code to try and replicate jQuery's .fadeIn()
and .fadeOut()
functions using CSS transitions to look better on touch devices.
Ideally I'd like to avoid using a library so that I can write exactly what I want, and as a learning exercise.
fadeOut
works well.
The idea for fadeIn
is to use CSS3 transitions to adjust the opacity of an element, after which the element will be set to display:block;
(using is-hidden
class) to ensure it's not still clickable or covering something beneath it.
fadeIn
is not working though. I think it is due to adding the is-animating
class at the same time as removing the is-hiding
class. The transitionEnd event never fires because a transition does not occur:
function fadeIn (elem, fn) {
var $elem = $(elem);
$elem.addClass('is-animating');
$elem.removeClass('is-hidden');
$elem.removeClass('is-hiding');
$elem.on(transitionEndEvent, function () {
$elem.removeClass('is-animating');
if (typeof fn === 'function') {
fn();
}
});
};
And the CSS
.is-animating {
@include transition(all 2000ms);
}
.is-hiding {
// Will transition
@include opacity(0);
}
.is-hidden {
// Won't transition
display: none;
}
Here's the code: CodePen link
Update: I have found what I'd describe as a hack, but that works very well: CSS3 replacement for jQuery.fadeIn and fadeOut
Working code after this fix: Fixed
A solution without setTimeout
would be very valuable though.
You may want to consider a couple of plugins that might take care of what you want:
jQuery.transition.js retrofits the existing jQuery animation methods to use CSS transitions in browsers that support them.
Transit adds a
transition
function you can use to define your own transitions. It uses jQuery's effect queue, so you can queue up the changeddisplay
value to run afteropacity
has finished transitioning.i don't know what you really wanna achieve but if your using css3 your using a modern browser. in that case pure css & javascript is a better solution.
it's all about how you write the css transition.
here is the js code
css code
and the html
here is an example.
http://jsfiddle.net/qQM5F/1/
I have managed to fix this by doing something that feels unnatural and hacky:
Adding the
setTimeout
function to the class that contains the transition-able property fixes the issue.Working code here: Codepen fixed code
Alternative solution using Keyframes
js
css3
example
http://jsfiddle.net/qQM5F/8/
here is a prototype
css
usage
the element you need to fade needs a class
fade
then toggle it withexample
http://jsfiddle.net/qQM5F/9/