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
}
Related
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.
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>
var mpegArray = ["1.m4a", "2.m4a", "3.m4a", "4.m4a", "5.m4a", "6.m4a", "7.m4a", "8.m4a", "9.m4a", "10.m4a"];
var choice = Math.floor(Math.random() * mpegArray.length);
function btnPlay_onClick() {
var player = document.getElementById('sound');
player.src = mpegArray[choice];
player.play();
player.addEventListener('ended', function () {
if (player.ended) {
mpeg();
}
}, true);
}
function btnN1_onClick() {
var Audio1 = document.getElementById("audio1");
Audio1.play();
if (choice == 0) {
document.getElementById("btnN1").src = "1GR.gif";
ans.innerText = CORRECT;
}
else
document.getElementById("btnN1").src = "1RD.gif";
ans.innerText = INCORRECT;
}
hiya the code here is meant to get number tiles to change colour based on if the requirements of the if statements are met. here the if statement is asking if button 1 is pressed after the audio file 1.m4a is played change the colour of he tile to green if not change it to red
You might be better served changing the css with a background colour/image instead of the src attribute.
document.getElementById("btnN1").style.backgroundColor = "green";
or
document.getElementById("btnN1").style.backgroundImage = "url('1GR.gif')";
EDIT: GiaFil7 is right. You're missing a closing } after the second if statement which might be causing your issue.
First let me describe the project I'm stuggeling with. English is not my foreign language so I do not know the exact name of the effect I am looking for.
Basicly I am creating a bingo type of game where the host can press on a button to start the bingo wheel. Eventually the wheel will stop and the word it has landed on is the chosen word for that round. After that, this word get removed from the game and the game starts over and over untill someone calls a bingo.
I started playing a bit around with some JSON data and how to remove the items from the array etc which is pretty easy to do. But now comes the part where I am struggeling the most. I have to create a kind of function that scrolls through all options like a wheel at a certain speed that eventually decreased in speed so it will land on the chosen word for this round. I created a fiddle with the code I currently have. Note that it's purely created for functionality instead of looks!
var json = {
"titles": [
"PLACEHOLDER_1",
"PLACEHOLDER_2",
"PLACEHOLDER_3",
"PLACEHOLDER_4",
"PLACEHOLDER_5",
"PLACEHOLDER_6",
"PLACEHOLDER_7",
"PLACEHOLDER_8",
"PLACEHOLDER_9",
"PLACEHOLDER_10",
"PLACEHOLDER_11",
"PLACEHOLDER_12",
"PLACEHOLDER_13",
"PLACEHOLDER_14",
"PLACEHOLDER_15"
]
}
$(document).ready(function() {
var app = new Bingo.init();
})
var Bingo = {
viewport: {
isMobile: 0,
isTablet: 0,
isDesktop: 1,
device: 'desktop',
browser: null
}
}
Bingo.init = function() {
Bingo.gameController.init();
};
Bingo.gameController = {
gameNames: {},
init: function() {
Bingo.gameController.general.saveJson();
$('.test').on('click', Bingo.gameController.array.pickRandomNumber)
},
general: {
saveJson: function() {
Bingo.gameController.gameNames = json.titles;
},
//General reset function
resetGame: function() {
Bingo.gameController.general.saveJson;
}
},
array: {
pickRandomNumber: function() {
//reset gamefield
Bingo.gameController.game.buildGame();
var gameNames = Bingo.gameController.gameNames;
var totalNames = gameNames.length;
//Pick a random number
var chosenNumber = Math.floor(Math.random() * totalNames);
Bingo.gameController.array.remove(chosenNumber)
},
remove: function(id) {
//remove chosen name from array
var gameNames = Bingo.gameController.gameNames;
var check = gameNames.indexOf(gameNames[id]);
Bingo.gameController.game.highlightName(id);
if (check != -1) {
gameNames.splice(check, 1);
Bingo.gameController.gameNames = gameNames;
}
}
},
game: {
buildGame: function() {
//build all the array entry's into the div
$('.page.main-game').empty();
var gameNames = Bingo.gameController.gameNames;
for (var i = 0; i < gameNames.length; i++) {
var item = '<div class="name-item" data-id="' + i + '">' + gameNames[i] + '</div>';
$('.page.main-game').append(item);
}
},
highlightName: function(id) {
//highlight the chosen number red
$('.name-item[data-id="' + id + '"]').css('color', 'red');
}
}
}
Fiddle link here
(I hope the link is correct, not using fiddle that much)
So now when you click on the 'play again' button you see that it wil highlight a word. What has to happen is when I press the play again button the red highlight has to go from the first div to the last and so forth untill it eventually stops at a div (which is chosen with the random number or something).
If someone can help me with this or could give me a hint in the right direction please let me know!
EXTRA: The app will eventually get a look like a scrollwheel that the iphone gets when you open a select box (hope you know what I am referring to). So thats why its a wheel of fortune-ish effect. If someone could provide me with the correct name for this let me know so I can adjust the title!
If any information is missing please let me know, i'd be happy to provide it! Thanks in regard!!
The basic ideas are (1) to keep the current index, so you can start the spin every time from that index, where 'spining' is just increasing that index or set to zero when reaching the maximal index; and (2) set a timeout for the next painting, and reduce that timeout everytime, until it's low enough.
JsFiddle Demo
HTML
<p><button onclick="w.spin(w.randomNext(), 8)">SPIN</button></p>
<ul id='wheel'>
<li>$100</li>
<li>$250,000</li>
<li>$25,000</li>
<li>$10,000</li>
<li>$1,000</li>
<li>$5</li>
<li>$2,000</li>
<li>30,000</li>
<li>$40</li>
</ul>
JavaScript
var wheelEl = document.getElementById('wheel');
function Wheel () {
this.current = 4;
}
Wheel.prototype.init = function () {
this.onItem();
}
Wheel.prototype.randomNext = function () {
return Math.floor(Math.random() * wheelEl.children.length);
}
Wheel.prototype.spin = function (next, itemsPerSecond) {
var timeout = setTimeout(onItem.bind(this), (1 / itemsPerSecond) * 1000);
function onItem () {
// stop if speed is low enough
if (itemsPerSecond < 1)
return;
// spin to next item
this.current ++;
if (this.current >= wheelEl.children.length)
this.current = 0;
// paint text
this.onItem();
// reduce speed
clearTimeout(timeout);
itemsPerSecond--;
timeout = setTimeout(onItem.bind(this), (1 / itemsPerSecond) * 1000);
}
}
// paints the index of this.current
Wheel.prototype.onItem = function () {
for (var i = 0 ; i < wheelEl.children.length ; i++)
wheelEl.children[i].style.color = (i == this.current) ? '#6d4321' : '#000000';
}
var w = new Wheel();
w.init();
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..