Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

bobcat
bobcat
13,623 Points

How do I add a sound when a button is clicked? - jQuery

I have a diceRoll() function and I want to add a nice dice rolling sound effect when the roll button is clicked.

Any ideas? I have done some googling but nothing that looks like its what I need.

Thanks

    //diceroll function
    function diceRoll() {
        return randomNumber = Math.floor(Math.random() * 20) + 1;
    }

    //create a diceroll event
    $('#dice-button').on('click', function(){
      diceRoll();
      $('#dice-div').html(randomNumber);
    })
bobcat
bobcat
13,623 Points

Ok, I figured it out with a little bit more googling and some help from SO. See the HTML and JS below.

https://stackoverflow.com/questions/11562509/adding-audio-to-click-event

          <audio id="mysoundclip" preload="auto">
              <source src="./assets/audio/ONEDICE.WAV"> </source>
          </audio>

    //create a diceroll event
    $('#dice-button').on('click', function(){
      diceRoll();
      $('#dice-div').html(randomNumber);
      //dice roll sound
      var audio = $("#mysoundclip")[0];
      audio.play();
    })

1 Answer

Steven Parker
Steven Parker
229,732 Points

Here's an easy way that requires no HTML:

const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
$('#dice-button').click(e => rollSound.play());

And a non-jQuery version:

const rollSound = new Audio("./assets/audio/ONEDICE.WAV");
document.getElementById('dice-button').addEventListener("click", e => rollSound.play());