-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
68 lines (62 loc) · 1.91 KB
/
script.js
File metadata and controls
68 lines (62 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class TypewriterEffect {
constructor(selector, options = {}) {
const {
prefix = '',
suffix = '',
phrases = [],
typingSpeed = 80,
deletingSpeed = 40,
pauseBetweenWords = 2000,
target = 'text' // 'placeholder' or 'text'
} = options;
this.el = document.querySelector(selector);
this.prefix = prefix;
this.suffix = suffix;
this.phrases = phrases;
this.typingSpeed = typingSpeed;
this.deletingSpeed = deletingSpeed;
this.pauseBetweenWords = pauseBetweenWords;
this.target = target;
this.charIndex = 0;
this.currentPhraseIndex = 0;
this.typing = true;
if (this.el) {
if (this.target === 'text') {
this.el.innerHTML = `<span class="typewriter-text"></span>`;
this.textEl = this.el.querySelector('.typewriter-text');
}
this.run();
}
}
updateContent(value) {
const fullText = this.prefix + value + this.suffix;
if (this.target === 'placeholder') {
this.el.placeholder = fullText;
} else if (this.target === 'text') {
if (this.textEl) this.textEl.textContent = fullText;
}
}
run() {
const currentPhrase = this.phrases[this.currentPhraseIndex];
if (this.typing) {
if (this.charIndex < currentPhrase.length) {
this.charIndex++;
this.updateContent(currentPhrase.slice(0, this.charIndex));
setTimeout(() => this.run(), this.typingSpeed);
} else {
this.typing = false;
setTimeout(() => this.run(), this.pauseBetweenWords);
}
} else {
if (this.charIndex > 0) {
this.charIndex--;
this.updateContent(currentPhrase.slice(0, this.charIndex));
setTimeout(() => this.run(), this.deletingSpeed);
} else {
this.typing = true;
this.currentPhraseIndex = (this.currentPhraseIndex + 1) % this.phrases.length;
setTimeout(() => this.run(), this.typingSpeed);
}
}
}
};