-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
82 lines (59 loc) · 2.21 KB
/
main.js
File metadata and controls
82 lines (59 loc) · 2.21 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const TypeWriter = function(txtElement, words, wait) {
this.txtElement = txtElement;
this.words = words;
this.txt = ''; // represents what is in the text area
this.wordIndex = 0; // which word we are on. formatted as an array
this.wait = parseInt(wait, 10); // needs to be an integer. base 10 number
this.type();
this.isDeleting = false; // represents the state whether it's deleting or not
}
// Type Method
TypeWriter.prototype.type = function() {
// console.log('test Type Method');
// get current word index
const currentWordIndex = this.wordIndex % this.words.length;
// console.log(currentWordIndex);
// get full text of the current word
const fullText = this.words[currentWordIndex];
// console.log(fullText);
// check if typed text is in deleting state
if(this.isDeleting) {
// remove a character
this.txt = fullText.substring(0, this.txt.length - 1);
} else {
// add a character
this.txt = fullText.substring(0, this.txt.length + 1);
}
// output text and insert txt into the text element (span)
this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>`;
// set initial type speed
let typeSpeed = 200;
if(this.isDeleting) {
typeSpeed /= 2; // half the typespeed if deleting is true
}
// if word is complete
if(!this.isDeleting && this.txt === fullText) {
// pauses at end
typeSpeed = this.wait;
// set delete to true
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
// move to the next word
this.wordIndex++;
// pause before start typing
typeSpeed = 500;
}
setTimeout(() => this.type(), 500)
}
// Init On Dom Load
document.addEventListener('DOMContentLoaded', init);
// Init App
function init() {
const txtElement = document.querySelector('.txt-type');
// parse through JSON.parse method
const words = JSON.parse(txtElement.getAttribute('data-words'));
const wait = txtElement.getAttribute('data-wait');
// initialize the typewriter by passing in all three data attributes
new TypeWriter(txtElement, words, wait);
}