0

How can I make a sound ("MySound.mp3") hidden in the background when a <a> element or <button> element with the id "click_sound" is clicked in JavaScript, is it possible?

Remember I want to make a sound in the background if an <a> or <button> are clicked!

The Code:

<html>
  <head></head>
  <body>
    <a id="click_sound">Click me</a>
  <button id="click_sound">Click me</button>
  </body>
</html>

The sound file name:
MySound.mp3

Rafał Nowosielski
  • 810
  • 10
  • 23
adel 3
  • 31
  • 6

1 Answers1

0

The easiest way to do what you are asking is to play the audio using javascript, when the button or a (or really any) tag is clicked. There are a few ways you could do this:

You could run the javascript in an onmouseup element:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="new Audio('path_to_audio_file.mp3').play()">Click me</a>
    <button id="click_sound" onmouseup="new Audio('path_to_audio_file.mp3').play()">Click me</button>
  </body>
</html>

or better yet, not run the audio constructor every time:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="audio.play()">Click me</a>
    <button id="click_sound" onmouseup="audio.play()">Click me</button>

      <script>const audio = new Audio('path_to_audio_file.mp3')</script>
  </body>
</html>

If you want to use an external script (either because you have other javascript, or you just prefer it that way, which I personally do) simply put it on the window object:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="window.audio.play()">Click me</a>
    <button id="click_sound" onmouseup="window.audio.play()">Click me</button>

      <script src='./path_to_file/somefile.js'></script>
  </body>
</html>

somefile.js:

  window.audio = new Audio('./path_to_audio/sound.mp3')

Please let me know if you need any more information about any of the above.

Note: You could also use:

document.getElementById('click_sound').addEventListener('mouseup', () =>  new Audio('path_to_audio_file.mp3').play())

To achieve the same thing.

For more information refer to this and this or look up "javascript 'Audio' constructor" and "onmouseup event".

MilesZew
  • 667
  • 1
  • 8
  • 21