work.suroh.tk/assets/js/interaction.js

124 lines
2.9 KiB
JavaScript

import {Synth} from '/assets/js/synth.js'
// audio for events
// AUDIO SETUP
const audioEngine = new (window.AudioContext || window.webkitAudioContext)()
audioEngine.suspend()
const masterGain = audioEngine.createGain()
const audioEl = document.querySelector('#audioToggle')
let audioAllowed = true
masterGain.gain.value = 0.9
masterGain.connect(audioEngine.destination)
const audioToggle = () => {
audioEl.classList.toggle('active')
if (audioEngine.state == 'suspended') {
audioEngine.resume()
audioAllowed = true
} else {
audioEngine.suspend()
audioAllowed = false
}
}
const audioEnable = () => {
if (audioEngine.state == 'suspended' && audioAllowed) {
audioEngine.resume()
}
}
audioEl.addEventListener('click', audioToggle)
// NAVIGATION
let primaryNav = document.querySelectorAll('nav#primary>span')
let subNav = document.querySelector('nav#sub')
let menuItem = document.querySelector('#menuItem')
let menuVoices = []
// check if any primaryNav items are active
const primaryActive = () => {
let active = false
for (let n of primaryNav) {
if (n.classList.contains('active')) {
active = true
}
}
return active
}
for (let n of primaryNav) {
// remove shitty firefox span spacing
n.nextSibling.parentNode.removeChild(n.nextSibling)
// create synthVoices per navItem
menuVoices[n.dataset.link] = new Synth(audioEngine)
menuVoices[n.dataset.link].gain.connect(masterGain)
// primary navigation click events
n.addEventListener('click', (e) => {
for (let _n of primaryNav) {
if (n === _n && n.dataset.link != '~') {
n.classList.toggle('active')
} else if (n.dataset.link == '~') {
window.location.href = '/'
} else {
_n.classList.remove('active')
}
}
// subnav is nav element
if (primaryActive()) {
subNav.classList.add('active')
} else {
subNav.classList.remove('active')
}
for (let s of subNav.children) {
if (s.id == n.dataset.link && primaryActive()) {
s.classList.add('active')
} else {
s.classList.remove('active')
}
}
})
// mouseover on primary nav for big botom text
n.addEventListener('mouseenter', () => {
// unsuspend sound on mouseenter
audioEnable()
if (n.dataset.link == '~') {
menuItem.textContent = '\u003C\u007E'
} else {
menuItem.textContent = n.dataset.link
}
menuItem.className = 'active'
menuVoices[n.dataset.link].noteOn()
})
n.addEventListener('mouseout', () => {
menuItem.className = 'inactive'
menuVoices[n.dataset.link].noteOff()
})
}
// SCROLL TO TOP NAVIGATION
const toTop = document.querySelector('nav#toTop')
toTop.addEventListener('click', (e) => {
window.scrollTo(0,0)
})
window.addEventListener('scroll', (e) => {
let scrollY = window.scrollY
if (scrollY > 50) {
toTop.classList.add('active')
} else {
toTop.classList.remove('active')
}
})