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
Sean Pierce Sumler
18,968 PointsJavaScript onmouseover to trigger audio element
Hi everyone.
I'm playing around with this simple grid-music-box thing that I made. I successfully used the javascript feature onmouseover to play an audio element while you hover over a certain div.
My problem is this- you must wait the entire duration of the sound before you can trigger the sound again. Is there any way to re-trigger the sound so you hover over the div a bunch of times quickly, and have the sound play many times over itself?
Any and all help is appreciated! Here is a link to what I'm working with currently ->
http://codepen.io/swollenboy/full/dYPRJo/
Thanks!!
2 Answers
Chyno Deluxe
16,936 PointsFirst of all. Great Pen. As a music producer I began playing with the sounds so kudos.
Now, to solve your problem. You'll need to reset the current time of the audio every time the element is hovered. View Below.
function playclipg4() {
var audio = document.getElementById("g4");
audio.currentTime = 0;
audio.play();
}
Secondly, I'd recommend not using inline javascript in your html to make editing alot simplier. Also, If your comfortable enough with javascript. I'd recommend you create a loop to cycle through the elements and add the event listeners as well.
I hope this helps.
Sean Pierce Sumler
18,968 PointsExcellent! Thanks for your response. Before I got your reply, I used a script on github called audio-fx.js to solve my issue.
But your method is way more streamlined. I think my load time on that page is pretty bad. I should clean up the code and make some other edits.
I'm just now getting into JS but I'm hooked :)
Chyno Deluxe
16,936 PointsThats way better. You might want to consider changing it to onclick tho for those checking your pen out on mobile. harder to hover on mobile to actually make use of it. Its still a bit hard now on desktop but other than that. Good work!