Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery's fadeIn and fadeOut be tweeked to use CSS transitions?

Tags:

jquery

css

I'm using jQuery for animations. Part of those use the .fadeIn and .fadeOut API. This works fine just about everywhere except on iOS devices. on iOS devices the fades look choppy and are generally not smooth at all, even over a 1 or 2 seconds fade.

Is there any way to rewrite or create a similar function that would use CSS transitions as they seem to be much smoother on on iOS than the method jQuery uses.

like image 632
Justin808 Avatar asked Jan 30 '26 05:01

Justin808


1 Answers

This is the best fadeIn/fadeOut using CSS3 transitions I've coded. It supports all of their signatures. So far, no bugs found. Feel free to reuse

var hasCSSTransitions = Modernizr.csstransitions;

hasCSSTransitions && (function ($) {
    $.fn.fadeIn = function (speed, easing, callback) {
        return this.filter(function (i, elem) {
                        return $.css(elem, 'display') === 'none' || !$.contains(elem.ownerDocument, elem);
                    })
                    .css('opacity', 0)
                    .show()
                    .end()
                .transition({
                    opacity: 1
                }, speed, easing, callback);
    };

    $.fn.fadeOut = function (speed, easing, callback) {
        var newCallback = function () {
            $(this).hide();
        };

        // Account for `.fadeOut(callback)`.
        if (typeof speed === 'function') {
            callback = speed;
            speed = undefined;
        }

        // Account for `.fadeOut(options)`.
        if (typeof speed === 'object' && typeof speed.complete === 'function') {
            callback = speed.complete;
            delete speed.complete;
        }

        // Account for `.fadeOut(duration, callback)`.
        if (typeof easing === 'function') {
          callback = easing;
          easing = undefined;
        }

        if (typeof callback === 'function') {
            newCallback = function () {
                $(this).hide();
                callback.apply(this, arguments);
            };
        }

        return this.transition({
            opacity: 0
        }, speed, easing, newCallback);
    };
}(jQuery));

This requires jQuery Transit plugin from Rico. It's just a wrapper with a similar signature than animate() but for using css3.

like image 58
Tom Roggero Avatar answered Jan 31 '26 19:01

Tom Roggero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!