Scope in JavaScript can be a little "unexpected". Variables (defined
using var) are scoped/exist within the functions they are defined in,
and any functions that are defined within that function. Since you're
using this functionality in other spots I think you understand that.

The setInterval (and setTimeout) functions can take a string, but as
you saw it it runs in the "global" window "context", so you should
just pass in the function you want to run.

So you should write something like (untested):

jQuery.fn.typewriter = function(speed) {
       return this.each(function(){

               var elem = jQuery.this;
               var contents = elem.html();
               var count = 1;

               if(contents.length){
                       elem.html("");

                       var interval = setInterval(addText, speed);
               }

               function addText(){

                       elem.html(contents.substr(0, count));

                       count++;

                       if(count > contents.length){
                               clearInterval(interval);
                       }
               }

       });
};

Karl Rudd

On Wed, Aug 20, 2008 at 7:09 AM, DanDan <[EMAIL PROTECTED]> wrote:
>
> Here's my code.  The plugin should take the text from a container,
> erase the container, then print out the text one character at a time
> in a typewriter fashion.  The problem is that setInterval() seems to
> think that addText() is undefined, because setInterval() runs at the
> 'window' scope level.  I had this function running fine as a normal
> program, but I'm unclear on how to convert it over to the plugin
> format and solve the scope issue.  thanks in advance.
>
> jQuery.fn.typewriter = function(speed) {
>        return this.each(function(){
>
>                var contents = jQuery(this).html();
>                var count = 1;
>
>                if(contents){
>                        jQuery(this).html("");
>
>                        var interval = setInterval("addText()", speed);
>                }
>
>                function addText(){
>
>                        jQuery(this).html(contents.substr(0, count));
>
>                        count++;
>
>                        if(count > contents.length){
>                                clearInterval(interval);
>                        }
>                }
>
>        });
> };
>

Reply via email to