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

Will Albertsen
Will Albertsen
3,872 Points

Playing audio files with mouseovers

I need to have an audio file play on a mouseover. Any suggestions for code I could use? I just completed the course on jQuery but I still don't know how I should go about doing this. Any help would be greatly appreciated. Thanks!

2 Answers

I wrote the code you will need. I've included the script code into the html for clarity but you can paste it in a separate js file if you want.

<!DOCTYPE html>
<html>
<head>
    <title>Play/Pause Audio</title>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
        $(document).ready(function(){

            //Plays the file when the mouse is over the element
            $("#song1").mouseover (function (){

                $("#song1")[0].play();

            });

            //Pause the file when the mouse leaves the element
             $("#song1").mouseleave (function (){

                $("#song1")[0].pause();

            });

        });

    </script>

</head>
<body>
    <audio id="song1" controls>
      <source src="Your Source File Here.mp3" type="audio/mpeg">
    </audio>



</body>
</html>
Will Albertsen
Will Albertsen
3,872 Points

Thank you so much! I appreciate your time.