I have a simple Javascript program that plays a sound when correct button is clicked in response to a question.
If the user answers a second question too quickly and clicks a second correct answer the sound doesnt play a second time as first play has not completed.
Do I need to disable the answer buttons for the duration of the sound?
Any other ways roound?
Suggestions please
Scruffy code added 27.9.2022
function setQuestion(){
// string question
var questionText =" x 3 = ";
questionText=aTimes[index]+ questionText;
document.getElementById("Question").innerHTML= questionText;
aAnswers[0]=(aTimes[index]*3);
aAnswers[1]=Math.floor((Math.random() *10) *(aTimes[index] + 1));
aAnswers[2]=Math.floor((Math.random() *10) * (aTimes[index] + 2));
shuffleArray(aAnswers)
document.getElementById("Answer1").innerHTML= aAnswers[0];
document.getElementById("Answer2").innerHTML= aAnswers[1];
document.getElementById("Answer3").innerHTML= aAnswers[2];
}
function answerCheck(poss){
//*****************************************************************
//*** does the button clicked match the correct multiple of 3
//*****************************************************************
if (poss.innerHTML==(aTimes[index]*3) ) {
changePicture();
index=(index+1);
**playAudio();**
resetButtons();
setQuestion() ;
if (index==10){
alert("done");
}
}
else{
alert("not a match");
poss.style.backgroundColor = "grey";
}
}
function resetButtons(){
document.getElementById("Answer1").style.backgroundColor = "#008CBA" ;
document.getElementById("Answer2").style.backgroundColor = "#008CBA";
document.getElementById("Answer3").style.backgroundColor = "#008CBA";
}
**function playAudio()** {
//************** Play a reward sound
var x = document.getElementById("myAudio");
x.play();
}
</script>
The HTML audio element probably isn't a great fit for what you want to do here. I'd recommend using a library like Howler.
Related
I would like to play a correct sound tone when user selects correct answer and play an incorrect sound tone when user gets wrong answer. However both audio plays when answer is clicked
var correctSound = document.getElementById('correctSound');
var incorrectSound = document.getElementById('incorrectSound');
function checkAnswer(selectedAnswer) {
var theCorrectAnswer = quizData[currentQuestion - 1].correctAnswer;
// turn the boxes red or green depending on if they are the correct answer
$(".answer-box").each(function(index) {
if ((index + 1) == theCorrectAnswer) {
$(this).addClass("correct");
correctSound.play();
} else {
$(this).addClass("incorrect");
incorrectSound.play();
}
});
if (selectedAnswer == theCorrectAnswer) {
// got it correct
score += 1;
$(".score").html(score);
} else {
// got it wrong so do nothing
}
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
I'm currently trying to make a song selection list where a user can hit a button to preview a song. I'm struggling with the logic behind setting a buttons innerHTML to read 'Stop preview' when that buttons song is playing and also have the buttons HTML change when a user clicks another button.
Currently my script looks something like:
var playedBy;
var song;
var playing = false;
var audioPlayer = document.getElementById("demo");
function setSong(value, idForPlayed) {
song = value;
audioPlayer.src = song;
audioPlayer.play();
playedBy = idForPlayed;
var currentIdPlayingValue = document.getElementById(idForPlayed).value;
console.log(currentIdPlayingValue);
}
function valueGetter(button) {
song = button.value;
button.className += " playing";
var idForPlayed = button.id;
var value = song;
setSong(value, idForPlayed);
}
function doEnd() {
playing = false;
console.log('we have an end');
document.getElementById('demo').pause();
document.getElementById('demo').currentTime = 0;
}
With the value of the buttons being the URL i'm passing the audio object.
Any help is appreciated here, very unsure on the approach i should take.
Thanks all!
Simple example in code pen : http://codepen.io/anon/pen/XXwXYV
You could toggle the innerHtml and all of the other buttons html on click.
Something like
$('.btn').on('click', function(){
//Add or remove a class for the clicked button to determine if it's playing.
$(this).toggleClass('playing');
if($(this).hasClass('playing')){
//Set all buttons back to play
//And probably call some sort of Stop Playing function
$('.btn').html('Play').removeClass('playing');
$(this).html('Stop Playing').addClass('playing');
}else{
$('.btn').html('Play').removeClass('playing');
}
});
I'm trying to work through an assignment to further my understanding of js but I'm running into some issues that are keeping me from final code. The code executes a short quiz- inputs from radio buttons are taken in and matched to an object containing answers, then outputting a final score.
code at http://jsfiddle.net/8ax9A/3/
issues I'm aware of now :
my $response variable doesn't seem to work.
var $response = $('[name=rad]:checked').val();
counter is listening for clicks through questions. After the last question, I want to report final score. I can't get counter to reach the end of questions + 1, and I cant get an accurate final score listener reported (var finalScore).
if ($response == parseInt(questions[counter].answer, 10)) {
finalScore++;
}
Those are just snippets so check out the fiddle for full code. I'd love some suggestions on how to understand where I'm going wrong.
Here is one way you could do it:
//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);
//functions
function answer(){
// if the user did not answer
if ($('input:radio:checked').length == 0){
alert('You have to answer!');
return;
}
var currentQ=questions[counter];
// if answer is correct
if($('[name=rad]:checked').val()==currentQ.answer){score++;}
counter++;
// if there are no questions left
if(counter >= questions.length) {displayResults(); return;}
loadQuestion();
}
function loadQuestion(){
// clear the radio buttons
$("input:checked").removeAttr("checked");
var currentQ=questions[counter];
// display the question
$('h1').text(currentQ.question);
$('#a1').text(currentQ.choices[0]);
$('#a2').text(currentQ.choices[1]);
$('#a3').text(currentQ.choices[2]);
}
function displayResults(){
$("h1").text("You've finished with a score of " + score + "!");
$('[name=rad], #a1, #a2, #a3, #next').remove();
}
JS Fiddle
In my drag and drop game there is a grid that is populated with words that are hidden from the user. The aim of the game is to spell these words with the aid of a sound and a picture.
When the user is spelling the word they should be able to replay the sound to help them. I had it working before but it has stopped working and I cannot work out why.
Here is the code that makes it work...
$(".minibutton2").click(function() {
var noExist = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('wordglow2');
if (noExist) {
$('.minibutton2').prop('disabled', true);
} else {
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
}
});
Here is a fiddle - http://jsfiddle.net/smilburn/m8Squ/6/
variable is
var pic = $("#mypic")[0]; // pic.show() exception
so; is pic.show() change jQuery(pic).show();
http://jsfiddle.net/m8Squ/9/
else and he can
var pic = $("#mypic").eq(0); // pic.show() not exception..