On line 1, I’ll create a variable named appBody to represent the body of my app and set it using the querySelector method with a parameter of “.main”. This is so whenever I connect an element to the body, “.main” id will be the first thing the element will snap to. Afterwards, I’ll create two variables each declared to a new audio instance. To do this I’ll type new Audio, and inside the parentheses, I’ll put the audio url inside of quotes (here is a reference to a MDN Doc for this). This way when I’m ready to have the sound play, I can just reference the variable name.
Now let’s write out a function! I’ll formulate one named useSound and make it an arrow function. I’ll now set up an invocation after the end of useSound so whatever elements I create will show up on the DOM when I refresh the page.
Inside of useSound, I’m going to create an element ‘div’ using the document.createElement() method to hold the play button. I’ll give it a classname for styling later.
I’ll also make a button element called “playBtn” so that when we click on it, we get sound to play. I’ll also give playBtn a classname.
To make the sound play, we need an event listener! You can use an onclick method, but in this case I’ll use addEventListener(). Within addEventListener, I’m going to give it two parameters: a “click” and an arrow function with an event passed in. The function will trigger the play() method on a “click”, and will play sound clip from the url defined by the sound1 variable on line 2.
Last, we should append the elements created to our original variable appBody. Like a stack of plates, playBtn has to append to playBtnDiv. Then playBtnDiv appends to appBody. Now refresh the page and click the button!
I hope this article helped in adding some audio to your app! To check out the full code for the image below, click here.