Spaces:
Running
Running
File size: 1,617 Bytes
2ce42d3 |
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 |
// music_controller.js
class MusicController {
constructor() {
this.bgMusic = document.getElementById('bgMusic');
this.musicToggle = document.getElementById('musicToggle');
this.isMusicPlaying = false;
this.initializeMusic();
this.setupEventListeners();
}
initializeMusic() {
if (this.bgMusic) {
this.bgMusic.volume = 0.5;
}
}
setupEventListeners() {
// Setup toggle button click handler
this.musicToggle.addEventListener('click', () => this.toggleMusic());
// Setup initial click handler for the whole document
document.addEventListener('click', () => {
if (!this.isMusicPlaying) {
this.playMusic().catch(error => console.log('Audio playback prevented:', error));
}
}, { once: true });
}
toggleMusic() {
if (this.isMusicPlaying) {
this.pauseMusic();
} else {
this.playMusic();
}
this.updateMusicIcon();
this.isMusicPlaying = !this.isMusicPlaying;
}
playMusic() {
return this.bgMusic.play();
}
pauseMusic() {
this.bgMusic.pause();
}
updateMusicIcon() {
const icon = this.musicToggle.querySelector('.iconify');
const iconName = this.isMusicPlaying ? 'mdi:speaker-off' : 'mdi:speaker';
icon.setAttribute('data-icon', iconName);
}
}
// Initialize the music controller when the document is ready
document.addEventListener('DOMContentLoaded', () => {
const musicController = new MusicController();
}); |