Search code examples
jqueryjquery-effects

Disable typewriter function if already typing


I have a jQuery function that emulates a typewriter effect, I have it being called on the .mouseup() handler function.

Now if the user releases the .mouseup() 2 times really fast the typewriter effect doubles up and types something like this: "ttyyppeewwrriitteerr eeffffeecctt".

It would be nice to know when it is done typing and disable mouse interaction while it is typing.

Here is my jQuery function: ( http://jsfiddle.net/MARm2/1/ )

//Typewriter Effect
$.fn.Typewriter = function(opts){
    var $this = this,
        defaults = { animDelay: 50 },
        settings = $.extend(defaults, opts);
    $.each(settings.text, function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + (letter!='\n'?letter:'<br />'));
        }, settings.animDelay * i);
    });
}

Here is the .mouseup() handler function:

$('#game_howto').mouseup(function(e) {
    $('#game_howto_slide1').Typewriter({
        animDelay: 50,
        text: 'Typewriter effect'
    });
});

Thanks in advance!


Solution

  • You can mark the element with the data attribute while you're typing and unmark it when you're done. Your modified code:

    $.fn.Typewriter = function(opts){
        var $this = this,
            defaults = { animDelay: 50 },
            settings = $.extend(defaults, opts);
    
        $this.data('typing', true); // we are typing!
    
        $.each(settings.text, function(i, letter){
            setTimeout(function(){
                $this.html($this.html() + (letter!='\n'?letter:'<br />'));
    
                if (i == settings.text.length  - 1) {
                    $this.data('typing', null); // this is the last letter, we are done typing!
                }
            }, settings.animDelay * i);
        });
    }
    
    $('#game_howto').mouseup(function(e) {
        if (!$('#game_howto_slide1').data('typing')) { // only run if not typing
            $('#game_howto_slide1').Typewriter({
               animDelay: 50,
                text: 'Typewriter effect'
            });
        }
    });