-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
93 lines (84 loc) · 2.05 KB
/
script.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
84
85
86
87
88
89
90
91
92
93
/**
* Variable initialization.
*/
var charsPerKeyStroke = 5;
var startIndex = 0;
var endIndex = 0;
var sourceCode = "";
var sourceElement;
var sourceContainer;
var fileName = "code.txt";
var cursorChar = "|";
/**
* Gets the contents which will appear as the user types or taps.
*/
function getFileContents() {
var rawFile = new XMLHttpRequest();
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
sourceCode = rawFile.responseText;
console.log(sourceCode);
}
}
};
rawFile.open("GET", fileName, true);
rawFile.send();
}
/**
* Gets the areas which will be updated on each keystroke or tap.
*/
function getElements() {
sourceContainer = document.getElementById("container");
sourceElement = document.getElementById("source");
}
/**
* Initializes variables and creates blinking cursor effect.
*/
function init() {
getFileContents();
getElements();
window.setInterval(updateCursor, 500);
}
/**
* Updates cursor position on each keystroke or tap.
*/
function updateCursor() {
var text = sourceElement.textContent;
var lastChar = text.charAt(text.length-1);
if (lastChar === cursorChar) {
sourceElement.textContent = text.substring(0,text.length-1);
}
else {
sourceElement.textContent += cursorChar;
}
}
/**
* Sets updated code.
*/
function updateScreen() {
endIndex += charsPerKeyStroke;
sourceElement.textContent = sourceCode.substring(startIndex, endIndex);
}
/**
* Updates scroll position to match code's height.
*/
function updateScrollPosition() {
window.scrollTo(0, sourceContainer.scrollHeight);
}
/**
* Updates all states.
*/
function update() {
updateScreen();
updateScrollPosition();
}
/**
* Runs application.
*/
function run() {
window.onload = init;
window.onkeydown = update;
window.ontouchstart = update;
}
run();