How to play a sound when an element is clicked in HTML page

Saturday February 22, 2014 ()

   How to play a sound when an element is clicked in HTML page
In this example we will demonstrate how to play a "click" sound when a link or other element is clicked in HTML pages. A sample code for jQueryMobile is also provided. An MP3 audio file is used play the actual sound. You have to have jQuery in your page for this to work.

Sound is played through HTML5 <audio /> tag but instead of embedding the tag manually, the tag is created via Javascript/JQuery. Below is how this is done.

<script>

    $(document).ready(function() {
        var obj = document.createElement("audio");
        obj.src="https://kahimyang.com/resources/sound/click.mp3";
        obj.volume=0.10;
        obj.autoPlay=false;
        obj.preLoad=true;       

        $(".playSound").click(function() {
            obj.play();
        });

    });

</script>

For best results place this code at the bottom of the page just before the closing </body> tag. In the example above, src attribute is the MP3 sound file and then we bind a click handler to class "playSound". This means that every element in the page with this class (or styleClass for JSF elements) will play a sound when clicked. If only anchors are desired, just replace "playSound" with "a.playSound" or just "a" to apply to all anchors. See example below.

<a href="#" class="playSound">Play</a>

For PrimeFaces menuitem see below.

<p:menuitem url="#" styleClass="playSound" value="Play" />

jQueryMobile

For jQueryMobile pages use the following code. Note that the following was tested in JQM 1.4.1 in desktop environment and Andriod 4.4 (GS4) only.

<script>

    $(document).on("pagecreate", function() {
        var obj = document.createElement("audio");
        obj.src="https://kahimyang.com/resources/sound/click.mp3";
        obj.volume=0.10;
        obj.autoPlay=false;
        obj.preLoad=true;
        
        $(".playSound").on("click tap", function () {
            obj.play();
        });           
    });

</script>

Here is a collection of sound files (wav and mp3). The website says, these are free.

http://www.soundjay.com/index.html

That's it good luck.


14,428

Comments (How to play a sound when an element is clicked in HTML page)