Fart

Episode #450 by Teacher's Avatar David Kimura

Summary

Ever wonder how you could add audio to interactions on a website. In this episode, we'll explore adding sounds whenever someone clicks on a link or button.
rails javascript april fools 5:44

Resources

Summary

# Terminal
yarn add fart

# app/javascript/application.js
import { mp3 } from "fart"

document.addEventListener("turbo:load", () => {
  const getRandomSound = () => {
    const randomIndex = Math.floor(Math.random() * mp3.sound.length);
    return [mp3.prefix, mp3.sound[randomIndex]].join("");
  };

  const playAudio = () => {
    const audio = new Audio();
    audio.src = getRandomSound();
    audio.play().catch(error => console.error("Error playing the audio:", error));
  };

  const selectors = ['a', 'button'];
  selectors.forEach(selector => {
    document.querySelectorAll(selector).forEach(element => {
      element.addEventListener('click', playAudio);
    });
  });
});