views:

20

answers:

1

here is a little demo of the problem: textAnimation Demo and here is the plugin code:

(function($) {
    $.fn.textAnimation = function(options) {
        // debug(this);
        // build main options before element iteration
        var opts = $.extend({}, $.fn.textAnimation.defaults, options);

        // iterate and reformat each matched element
        return this.each(function() {
            $toAnimate = jQuery(this);
            $toAnimateText = $toAnimate.text();
            $toAnimateTextLength = $toAnimateText.length;
            $toAnimate.text("");

            var show = false;
            var counter = 0;
            var char = new Array();
            var newColor;
            var $animation = null;

            // build element specific options
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            for (i=0; i<$toAnimateText.length; i++) {
                char[i] = $toAnimateText.charAt(i);
                $toAnimate.append('<span class="' + i +  '">' + char[i] + '</span');
            }

            function runIt(show) {
                $animation = $toAnimate.children('span.' + counter);

                newColor = (show == true) ? o.fromColor : o.toColor;

                $animation
                    .css("color", newColor)
                    //.delay(120, countUp) // this seems to be a jquery bug - after the first loop countUp is not called
                    .animate({left:'0'}, 120, countUp) // took the left because it makes no problem in all browsers

                function countUp() {
                    counter++;

                    if (counter >= $toAnimateTextLength) {
                        counter = 0;
                        show = (show == false) ? true : false;
                    }

                    runIt(show);
                };
            };

            runIt(show);
        });
    };

    //
    // private function for debugging
    //
    function debug($obj) {
    if (window.console && window.console.log)
        window.console.log('textAnimation selection count: ' + $obj.size());
    };   

    //
    // plugin defaults
    //
    $.fn.textAnimation.defaults = {
        fromColor: '#223139',
        toColor: '#e6772b'
    };
//
// end of closure
//
})(jQuery);
+1  A: 

The main problem is here:

$toAnimate = jQuery(this);

It's declaring this as a global variable, one that's replaced every loop, so it ends up only animating the last one correctly. The fix is simple though, just add var which makes it the local variable it was intended to be, like this:

var $toAnimate = $(this);

I'm using $ here because we're in the closure and the rest of the plugin's using it...this is just a consistency change. You can see the fixed version working here.

Nick Craver
thx a lot, saved my day
Stefan Kandlbinder
@Stefan - welcome :)
Nick Craver