-
Notifications
You must be signed in to change notification settings - Fork 0
/
primary.js
69 lines (54 loc) · 1.5 KB
/
primary.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
document.body.addEventListener('touchmove', ev => ev.preventDefault())
const elements = {
audio: document.querySelector('audio'),
button: document.querySelector('button'),
progress: document.querySelector('progress'),
};
let state = {
playing: false,
position: 0,
};
function reset() {
elements.audio.pause();
state.isPlaying = false;
state.position = 0;
render();
}
function render() {
elements.progress.value = state.position * 100;
if (state.isPlaying) {
elements.progress.classList.add('is-playing');
elements.button.textContent = 'Stop';
} else {
elements.progress.classList.remove('is-playing');
elements.button.textContent = 'Start';
}
}
function onTimeupdate(event) {
state.position = event.srcElement.currentTime / event.srcElement.duration;
render();
}
function onClickPlayButton(event) {
if (state.isPlaying) {
elements.audio.pause();
} else {
elements.audio.currentTime = 0;
elements.audio.play();
}
state.isPlaying = !state.isPlaying;
render();
}
function onClickProgress(event) {
if (!state.isPlaying) return;
state.position = event.clientX / document.body.clientWidth;
elements.audio.currentTime = elements.audio.duration * state.position;
render();
}
function init() {
render();
elements.audio.addEventListener('timeupdate', onTimeupdate);
elements.audio.addEventListener('ended', reset);
elements.button.addEventListener('click', onClickPlayButton);
elements.progress.addEventListener('click', onClickProgress);
}
init();