-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
64 lines (53 loc) · 1.65 KB
/
index.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
const honkify = (elementToHonkify = false) => {
if (typeof window === 'undefined') {
console.warn('honkify only works in the browser.');
console.warn('I mean... honk!');
return;
}
//check if the user is on iOS Safari, if they are, we initiate the safari audio "hack"
const ua = window.navigator.userAgent;
const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
const webkit = !!ua.match(/WebKit/i);
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
const audio = new Audio(
'https://res.cloudinary.com/jlengstorf/video/upload/q_auto/v1569957993/honk-sound.mp3'
);
const defaultSelectors = [
'a',
'button',
'input[type="submit"]',
'input[type="reset"]',
'input[type="button"]'
];
/**
* if the platform is iOS Safari, we quickly play, pause, reset the audio object
* this allows it to be playable the next time an user clicks a link
*/
if (iOSSafari) {
console.log('Honk! This is safari');
document.body.addEventListener('touchstart', () => {
audio.play();
audio.pause();
audio.currentTime = 0;
});
}
const everythingClickable = Array.from(
(elementToHonkify || document).querySelectorAll(defaultSelectors.join(','))
).filter(item => !item.classList.contains('no-honk'));
const honk = event => {
event.preventDefault();
event.stopImmediatePropagation();
audio.play();
return false;
};
everythingClickable.forEach(link => {
link.addEventListener('click', honk);
});
const dehonk = () => {
everythingClickable.forEach(link => {
link.removeEventListener('click', honk);
});
};
return dehonk;
};
export default honkify;