How do i add sound to my replits

let’s say you make a button <button> click me now please click me now please click me please just click me click me </button and you want to build it to make a sound. how do i do that?

You can add this to your html file

<button onclick="document.getElementById('myAudio').play()">Play sound</button>

<audio id="myAudio">
  <source src="file.mp3" type="audio/mpeg">
</audio>

Then you could replace “file.mp3” with your own audio file.

According to @MattDESTROYER it’s better to use event listeners:

<button id="audioButton">click me now please click me now please click me please just click me click me</button>

<audio id="myAudio">
  <source type="audio/mpeg" src="myAudio.mp3">
</audio>

<script type="text/javascript">
  const audioButton = document.getElementById("audioButton")
  const audio = document.getElementById("myAudio")

  audioButton.addEventListener("click", () => {
    audio.play()
  }
</script>
2 Likes

Yep, for one, the other two methods of adding an event listener are actually identical, as in they do the exact same thing. They both assign to the on<event> property of a DOM Element. This is considered bad practice for a number of reasons, feel free to read this article (you can easily find more with a quick Google search.)

It comes down to a few main points:

  1. In-line JavaScript within HTML is considered bad practice. (In-line CSS is also considered bad practice.) Your HTML can quickly get very messy.
  2. It is very clear what function handles the event for what element with on<event>, but you then have to find the function and find the specific JavaScript script it is in so it’s probably worse in the long run in terms of organisation.
  3. Probably the most important of all. onclick (both in HTML and in JavaScript) is a property of an (DOM Element) object. That means, if you reassign to it, you overwrite it, whereas with addEventListener you can have multiple event listeners for the same event (which can often happen if you are building something on top of something else) and it means you can’t accidentally reassign the event to something else, somewhere else, breaking your page.
  4. There is actually potentially a performance improvement using addEventListener over onclick… but if there is, it’s incredibly minor to the point the difference is it’s negligible.
1 Like

I know. It pained me to do it, lol. But it’s a lot simpler to type than telling them to create a whole new js file imo.

1 Like

Personally, I think your example is fine, it’s more so in-line code within attributes, or if the in-line code gets too long and clutters that HTML. :slight_smile:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.