Skip to content

Commit b1c82c2

Browse files
authored
Create typewriter.js
1 parent f72463c commit b1c82c2

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

typewriter.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
var TxtType = function(el, toRotate, period) {
2+
this.toRotate = toRotate;
3+
this.el = el;
4+
this.loopNum = 0;
5+
this.period = parseInt(period, 10) || 2000;
6+
this.txt = '';
7+
this.tick();
8+
this.isDeleting = false;
9+
};
10+
11+
TxtType.prototype.tick = function() {
12+
var i = this.loopNum % this.toRotate.length;
13+
var fullTxt = this.toRotate[i];
14+
15+
if (this.isDeleting) {
16+
this.txt = fullTxt.substring(0, this.txt.length - 1);
17+
} else {
18+
this.txt = fullTxt.substring(0, this.txt.length + 1);
19+
}
20+
21+
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
22+
23+
var that = this;
24+
var delta = 200 - Math.random() * 100;
25+
26+
if (this.isDeleting) { delta /= 2; }
27+
28+
if (!this.isDeleting && this.txt === fullTxt) {
29+
delta = this.period;
30+
this.isDeleting = true;
31+
} else if (this.isDeleting && this.txt === '') {
32+
this.isDeleting = false;
33+
this.loopNum++;
34+
delta = 500;
35+
}
36+
37+
setTimeout(function() {
38+
that.tick();
39+
}, delta);
40+
};
41+
42+
window.onload = function() {
43+
var elements = document.getElementsByClassName('typewrite');
44+
for (var i=0; i<elements.length; i++) {
45+
var toRotate = elements[i].getAttribute('data-type');
46+
var period = elements[i].getAttribute('data-period');
47+
if (toRotate) {
48+
new TxtType(elements[i], JSON.parse(toRotate), period);
49+
}
50+
}
51+
// INJECT CSS
52+
var css = document.createElement("style");
53+
css.type = "text/css";
54+
css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #fff}";
55+
document.body.appendChild(css);
56+
};

0 commit comments

Comments
 (0)