How do I play an audio file with jQuery? -
i'm having difficult time getting audio work jquery. i've tried both .wav , .ogg formats. (firefox 19.0.2)
clicking start button yields:
typeerror: buzzer.play not function
i'm not sure if jquery selectors return array, i've tried capture audio file both:
var buzzer = $('buzzer');
and
var buzzer = $('buzzer')[0];
regardless, can't audio elements play.
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> </head> <body> <audio id="buzzer" src="buzzer.ogg" type="audio/ogg">your browser not support <audio> element.</audio> <form id='sample' action="#" data-ajax="false"> <fieldset> <input value="start" type="submit"> </fieldset> </form> <script type="text/javascript"> var buzzer = $('buzzer')[0]; $(document).on('submit', '#sample', function() { buzzer.play(); return false; }); </script> </body> </html>
you forgot hash #
in id selector :
var buzzer = $('#buzzer')[0]; $(document).on('submit', '#sample', function() { buzzer.play(); return false; });
and document.getelementbyid('buzzer')
seem more appropriate!
i'd change html to:
<audio id="buzzer" src="buzzer.ogg" type="audio/ogg"></audio> <input type="button" value="start" id="start" />
and do:
$('#start').on('click', function() { $('#buzzer').get(0).play(); });
Comments
Post a Comment