forked from FBalint/button
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscripts.js
More file actions
92 lines (77 loc) · 2.26 KB
/
scripts.js
File metadata and controls
92 lines (77 loc) · 2.26 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
83
84
85
86
87
88
89
90
91
92
const downSound = new Audio('./assets/key-down.mp3');
const upSound = new Audio('./assets/key-up.mp3');
downSound.preload = 'auto';
upSound.preload = 'auto';
const el = document.getElementById('button');
// Track button press state
let isPressed = false;
function playSound(audio) {
audio.currentTime = 0;
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch(error => {
console.warn('Audio playback failed:', error);
});
}
}
function playDownSound() {
if (!isPressed) {
isPressed = true;
/* __active to support Android browsers */
el.classList.add('__active');
playSound(downSound);
}
}
function playUpSound() {
if (isPressed) {
isPressed = false;
/* __active to support Android browsers */
el.classList.remove('__active');
playSound(upSound);
}
}
el.addEventListener('mousedown', playDownSound);
document.addEventListener('mouseup', playUpSound);
let touchTarget = null;
el.addEventListener('touchstart', (e) => {
// Disabled text selection on iOS Safari
e.preventDefault();
// Remember the target element to handle touchend
touchTarget = e.target.parentElement;
playDownSound()
}, { passive: false });
el.addEventListener('touchend', playUpSound);
el.addEventListener('touchcancel', playUpSound);
// Reset button state when browser/tab loses focus
window.addEventListener('blur', playUpSound);
// Handle visibility change (when tab becomes hidden)
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
playUpSound()
}
});
// Handle click event
function handleClick() {
const href = el.dataset.href
if (href) {
setTimeout(() => {
window.location.href = href
}, 300)
}
}
function touchClick(e) {
if (e.changedTouches) {
const touch = e.changedTouches[0];
const target = document.elementFromPoint(touch.clientX, touch.clientY).parentElement;
if (target !== touchTarget) {
touchTarget = null;
return
}
}
handleClick();
}
if ('ontouchend' in document.documentElement) {
el.addEventListener('touchend', touchClick);
} else {
el.addEventListener('click', handleClick);
}