简体   繁体   中英

Typed.js - how to call function onClick multiple times

I'm using typed.js .

I want to run a function when a button is clicked. But I can only get the typed function to work once on the first click.

$(function(){
    var options = {
        strings: ["First sentence.", "Second sentence."],
        typeSpeed: 0
    }
    $("button").click(function(){
        $(".element").typed(options);
    });
});

See this fiddle for example: http://jsfiddle.net/mattboldt/tcRUG/

Type.js is not giving any way to do so. I tried using its api but it is using seTimeout everywhere and behaves asynchronously and not giving any promise/deferred object. To get it work one solution is to remove the element and create again. Personally i dont like this solution, looks hacky but it gets the job done

$(function(){
    var options = {
        strings: ["First sentence.", "Second sentence."],
        typeSpeed: 0,
        callback: function(){
            var x = $(".element").text();
            $("#maindiv").html("");
            $("#maindiv").append('<span class="element">'+x+'</span>');
        }
    }
    $("button").click(function(){ 
        $(".element").text('');
       $(".element").typed(options);        
    });
}); 

in HTML

<div id="maindiv"><span class="element"></span></div>
<button>Type!</button>

I recently had a similar problem. I implemented the answer but I also wanted the previous string to 'stick'.

For example, onclick I wanted typed to backspace the previous string before typing the new string.

I added this to init of typed

// Set the default string
if(self.isDefaultString) {
    self.strPos = self.strings[self.sequence[self.arrayPos]].length;

    if (self.isInput) {
        self.el.val(self.strings[self.sequence[self.arrayPos]]);
    } else if (self.contentType === 'html') {
        self.el.html(self.strings[self.sequence[self.arrayPos]]);
    } else {
        self.el.text(self.strings[self.sequence[self.arrayPos]]);
    }
}

and this to when the typed object is initiated

// default string of text
this.isDefaultString = this.options.isDefaultString;

then implemented typed like this

$("#contact header b").typed({
     strings: ["s1", "s2"],
     isDefaultString: true,
     typeSpeed: 30,
     startDelay: 250,
     showCursor: false
});

The result is that I would start with the string "s2" on the screen then typed would delete it and type "s1".

This is useful because if you want to call typed later on click. You can set the default to be "s2". Then typed will delete "s2" and print "s3".

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