Last active
September 26, 2016 17:06
-
-
Save AdonaiAraya/1a2519d6c4a9db2d7a45bf658cfd32d8 to your computer and use it in GitHub Desktop.
An angular 2 directive for gettting a type writter effect. Example: http://embed.plnkr.co/mQfnYYiFFGzTcJTSLpay/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, Renderer, Input, OnInit } from "@angular/core"; | |
@Directive({ | |
selector: "[typewritter]" | |
}) | |
export class TypewritterDirective implements OnInit{ | |
@Input("quotes") quotes : string[] = []; | |
private writtingSpeed : number = 225; | |
private deletingSpeed : number = 80; | |
private timelapseBetweenWords = 500; | |
private quoteCount : number = 0; | |
private currentQuoteIndex : number = 0; | |
constructor(private element : ElementRef, private renderer : Renderer){} | |
ngOnInit(){ | |
console.log(this.renderer); | |
if(this.quotes.length > 0) this.typeQuote(); | |
} | |
private typeQuote(){ | |
if(this.currentQuoteIndex > this.quotes[this.quoteCount].length) { | |
this.currentQuoteIndex = this.quotes[this.quoteCount].length; | |
setTimeout(() => this.deleteQuote(), this.timelapseBetweenWords); | |
} | |
else { | |
let str = this.quotes[this.quoteCount].substr(0, this.currentQuoteIndex); | |
this.currentQuoteIndex++; | |
this.renderer.setText(this.element.nativeElement, str); | |
setTimeout(() => this.typeQuote(), this.writtingSpeed); | |
} | |
} | |
private deleteQuote(){ | |
if(this.currentQuoteIndex >= 0){ | |
let str = this.quotes[this.quoteCount].substr(0, this.currentQuoteIndex); | |
this.currentQuoteIndex--; | |
this.renderer.setText(this.element.nativeElement, str); | |
setTimeout(() => this.deleteQuote(), this.deletingSpeed); | |
} | |
else { | |
this.currentQuoteIndex = 0; | |
this.quoteCount++; | |
if(this.quoteCount >= this.quotes.length) this.quoteCount = 0; | |
this.typeQuote(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment