audio - Adding sound when button is clicked in javascript -
i've started coding. i've made quiz , want sound played when students click correct answer, , sound played when click incorrect answer. i've found posts online not working. can help? thank in advance!
javascript:
function checkanswer(){ myanswer=$('#inputbox').val(); if(myanswer.slice(myanswer.length-1,myanswer.length)==" "){ myanswer=myanswer.slice(0,myanswer.length-1);} if(currentanswer==myanswer){ score++; $('#feedback').append('<img src="tick.png">'); $('#inputbox').css("background-color","green"); $('#inputbox').css("color","white"); } else{ $('#feedback').append('<img src="cross.png">'); $('#inputbox').css("background-color","red"); $('#inputbox').css("color","white"); $('#inputbox').val($('#inputbox').val()+" (ans= "+currentanswer+")"); } $('#message').append('press enter again continue'); $("#inputbox").prop('disabled', true); $("#gamearea").focus(); gameposition=2; if(currentquestionnumber==numberofquestions){gameposition=3;} }//checkanswer
html:
<!doctype html> <head> <title>quiz</title> <meta name=viewport content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="main.css" rel="stylesheet" type="text/css"/> <link href="mainclock.css"rel="stylesheet"type="text/css"/> <script src="jquery.js"></script> <script src="controller.js"></script> </head> <body> <div id="gamearea" tabindex="1"></div> <div id="mainstage"> </div> </body>
apparently using jquery . suggest use jquery based code handle process because of less codding , on . copy below code @ bottom of yours , call when ever need hear sound:
function rightanswerchosen(){ var audiofilename="audio.mp3"; $("body").append("<audio src="+audiofilename+" autoplay=true loop=false/>"); }
its simple! do'nt forget put audio file in same directory(folder) page in and replace it's name 'audio.mp3'.
to have more functionality can add more attributes (ex:loop-preload-volume...) in audio tag wish .
that's it!
Comments
Post a Comment