Search code examples
audiojqueryplaysound

Seelcting audio elements using classes and playing them


I have sound clip registered in html:

<audio class="aaa" id="sss"><source src="url/sound.wav"/></audio>
<script type="text/javascript">var sss = document.getElementById("sss"); sss.volume='0.1';</script>

This sound can be played with mouseenter event on the certain div:

$('#divid').mouseenter(function () {
    $(sss.play());
});

How can this be achieved with audio class instead of id?

edit: solved


Solution

  • .play() is a method of the HTMLAudioElement object not the jQuery object, jQuery wrapper doesn't do anything here, as you are passing retuned value of the .play() method to it, you can select the element(s) using jQuery, gets DOM element object(s) from the collection and call the .play() method on it:

    $('audio.aaa').get(0).play(); // works for the first matched element in the collection
    

    If there are several elements, you can iterate through the collection using .each() method:

    $('audio.aaa').each(function() {
       // `this` keyword here refers the HTMLAudioElements
       this.foo();
    });