Code Snippets
Play a Sound on Button Click

Play a Sound on Button Click

with
Javascript
in
Have a sound play whenever you click on a specified button/element

See it in action

This code allows you to set up any element you like as a trigger to play a sound of your choice on click. Click the button in the frame below to see it in action.

The code

Copy the code below to the before </body> tag of the page you need the functionality on.



<script>

const audio = new Audio("https://drive.google.com/uc?export=download&id=1qvsdI16mdVrfk-xemqUL72UF56Q_IvQB");
const buttons = document.querySelectorAll(".button");

buttons.forEach(button => {
  button.addEventListener("click", () => {
    audio.play();
  });
});
 
 </script>
 
 

Setting it up

  1. Create the element that you want to trigger the sound on click. This can be any element you like.
  2. Assign a class to the trigger in Webflow designer. In the case of the code above, any element with the class of <span class="class-tile">button</span> will trigger the sound on click. You can change this class to anything you like just make sure you update it in your code as well.
  3. Get your sound ready and paste its url in the brackets following "Audio" in your code (currently occupied by the google drive url). You can host this sound wherever you like, I usually use Google Drive for this. If you do use Google Drive, you will first need to run your src url through a Direct Link Generator before your sound will play.
  4. Publish and click away!