-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
83 lines (63 loc) · 2.18 KB
/
main.js
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
83
import './style.css'
//utility function to select dom elements
const $ = (selector) => {
const isString = typeof selector === 'string'
if (!isString) throw new Error(`Trying to select a ${typeof selector}`)
return document.querySelector(selector)
}
//define a sentence to typewrite
const sentence = 'This is a typewritting animation proof of concept . . .'
//split each word into an array
const wordsList = sentence.split(' ')
//global variables
let wordIndex = 0
let letterIndex = 0
let currentWord = ''
let slicedWord = ''
/**
* type() recursively calls itself until it finishes adding each letter to the DOM element that
* beholds the displayed word.
* Whenever it hits the last character it calls the erase() function which does exacly the oposite
* of type() but with the same logic.
* erase() recursively calls itself, deleting a character from the string in each iteration until
* it has no characters to delete. Whenever the function finishes deleting all the letters and
* isEraseFinished the function calls type() instead of itself.
*
* And the cycle repeats.. =D
*/
const type = () => {
if (isLastWord()) resetWordIndex()
setCurrentWord()
writeOneLetter()
if (hasTypingFinished()) {
setTimeout(erase, currentWord.length * 120)
} else {
setTimeout(type, 90)
}
}
const erase = () => {
eraseOneLetter()
if (hasEraseFinished()) {
nextWord()
resetLetterIndex()
setTimeout(type, 90)
} else {
setTimeout(erase, 50)
}
}
const writeOneLetter = () => {
slicedWord = currentWord.slice(0, letterIndex++)
$('.highlight-word').textContent = slicedWord.toUpperCase()
}
const eraseOneLetter = () => {
slicedWord = currentWord.slice(0, letterIndex--)
$('.highlight-word').textContent = slicedWord.toUpperCase()
}
const hasEraseFinished = () => slicedWord.length === 0
const hasTypingFinished = () => slicedWord.length === currentWord.length
const isLastWord = () => wordIndex === wordsList.length
const nextWord = () => wordIndex++
const resetLetterIndex = () => letterIndex = 0
const resetWordIndex = () => wordIndex = 0
const setCurrentWord = () => currentWord = wordsList[wordIndex]
type()