Note that there are some explanatory texts on larger screens.

plurals
  1. POSelect multiple divs but play different audio with jQuery
    primarykey
    data
    text
    <p>I'm currently trying to create a soundboard just to learn some more advanced jQuery techniques. </p> <p>Currently, each div is associated to a jQuery function that represents a sound. When the div is clicked, the respective sound is played. In it's current state, I have each function written as separate functions, which overtime, will lead to redundant code. </p> <p>Curious if there is a way to abstract the function to build out one function that represents any div click that will then initiate the appropriate audio file. </p> <p>See code below: </p> <p>HTML</p> <pre><code>&lt;div id="wrapper"&gt; &lt;h1&gt;Soundboard Trials&lt;/h1&gt; &lt;div id="boxes"&gt; &lt;li id="nyan"&gt;&lt;audio src="song.mp3"/&gt;&lt;/li&gt; &lt;li id="duck"&gt;&lt;audio src="duck.mp3"/&gt;&lt;/li&gt; &lt;li id="duck"&gt;&lt;audio src="cat.mp3"/&gt;&lt;/li&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS </p> <pre><code>#wrapper { width: 800px; margin: auto; } #boxes { padding: 0; margin: 50px auto; list-style: none; } #boxes li { width: 150px; height: 150px; background-color: #aaa; margin: 5px; float: left; cursor: pointer;} </code></pre> <p>jQuery</p> <pre><code>$(function(){ $("#nyan").click(function(){ var audio = $('audio')[0]; if (audio.paused){ audio.play(); } else { audio.pause(); } }); $("#duck").click(function(){ var audio = $('audio')[1]; if (audio.paused){ audio.play(); } else { audio.pause(); } }); $("#cat").click(function(){ var audio = $('audio')[2]; if (audio.paused){ audio.play(); } else { audio.pause(); } }); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload