简体   繁体   中英

Pausable typewriter effect in jQuery

I'm using the typewriter plugin from Jason Frame's Grab Bag .

However, I now find myself in a situation where I need to be able to pause and resume this typewriter at any point during its run.

Ideally, I'd have .typewriter("pause") to pause it, and .typewriter("resume") to resume the animation from where it left off.

I've tried setting a paused variable within the plugin, and leaving the interval running with a check for the variable each iteration -- if true, do nothing.

However, due to my lack of skills in making jQuery plug-ins, each time I call the function to pause the typewriter, it just starts all over again. I suspect the paused variable gets reset.

How would I go about making this plugin pausable?

jsBin demo

Add this 2 lines here:

(function($) {      
    $.fn.typewriter = function() {
        this.each(function() {
            var $ele = $(this), str = $ele.text(), progress = 0;
            $ele.text('');
            timer = setInterval(function() {
              if(pause===false){    // ADD THIS LINE ////////////////////////
                  $ele.text(str.substring(0, progress++) + (progress & 1 ? '_' : ''));
                  if (progress >= str.length) clearInterval(timer);
              }                     // ADD THIS LINE ////////////////////////
            }, 100);
        });
        return this;
    };   
})(jQuery);

$("#typewriter").typewriter(); // run your plugin

and I created this:

var pause = false;
$('#play_pause').click(function(){
  pause= !pause ? true : false;    // toggle true/false pause states
});

EDIT: find a better plugin-like solution in the comment below!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM