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

Patrick Johnson
Patrick Johnson
9,505 Points

Select multiple divs to play audio in jQuery

Hey All,

Having some issues with trying to create code in jQuery that will allow me to create one, abstracted selection on a set of <div> elements that will initiate their respective audio pieces.

In its current state I created unique functions that play audio for their respective divs using the 'click' function. My only issue with this, it's not DRY.

HTML

<div id="boxes">
<li id="nyan"><audio src="song.mp3"/></li>
<li id="duck"><audio src="duck.mp3"/></li>
<li id="duck"><audio src="cat.mp3"/></li>
</div>

CSS

#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;

}

jQuery

$(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();
        }
});
});

1 Answer

Alexander Smith
Alexander Smith
2,769 Points

Not a javascript expert so sorry it's just theory here. Can you not set the ids to be variables in the jquery and have jquery check which div it's in?