I've been having this problem where audio wouldn't play. I am trying to get a random sound to play but nothing happens when I click on the image (which has an onclick="playRandomSound()"). This is my code.
var sound1 = new Audio("InDeed.wav");
var sound2 = new Audio("Indeed2.wav");
var sound3 = new Audio("Yeeees.wav");
var sound4 = new Audio("girl_shut_up.wav");
var sound5 = new Audio("imhmmm.wav");
var randomizer;
function playRandomSound(){
randomizer = Math.floor(Math.random()*5);
if (randomizer === 0){
sound1.play();
} else if (randomizer == 1){
sound2.play();
} else if (randomizer == 2){
sound3.play();
} else if (randomizer == 3){
sound4.play();
} else if (randomizer == 4){
sound5.play();
}
}
body {
background: white;
}
#rokas {
height: 100vh;
}
<HTML>
<HEAD>
</HEAD>
<BODY>
<img src="https://i.imgur.com/4lO3dpT.jpg" id="rokas" onclick="playRandomSound()">
</BODY>
</HTML>
Please try to update your code like this:
html:
<audio style="display: none;" id="sound"></audio>
js:
function playRandomSound () {
var sound = document.getElementById('sound');
randomizer = Math.floor(Math.random()*5);
if (randomizer === 0){
sound.src = sound1;
} else if (randomizer == 1){
sound.src = sound2;
} else if (randomizer == 2){
sound.src = sound3;
} else if (randomizer == 3){
sound.src = sound4;
} else if (randomizer == 4){
sound.src = sound5;
}
sound.load();
sound.play();
}
Hope it helps.
Add the tag...
<audio id="audioPlaceHolder" src="InDeed.wav" autostart="false" ></audio>
You can dynamically change the src from your JavaScript.
For playing it...
var sound = document.getElementById('audioPlaceHolder');
sound.play();
enjoy!
Related
I am writing a dictionary program using CefSharp by C#. When the dictionary page(i.e.[Longman-love][1]) is loaded I want it could play its pronounce automatically(by clicking the pronouce icon using JavaScript). Here are related codes:
C# part:
browser.FrameLoadEnd += (sender, args) =>
{
//Wait for the MainFrame to finish loading
if (args.Frame.IsMain)
{
browser.ExecuteScriptAsync("document.getElementsByClassName('amefile')[0].click();");
}
};
JavaScript part(I copyed it from web and added some 'alert's for debugging the program):
$(document).ready(function(){
var audio = null;
$(".speaker").click(function(){
alert('x');
var src_mp3 = $(this).attr("data-src-mp3");
if (supportAudioHtml5())
playHtml5(src_mp3);
else if (supportAudioFlash())
playFlash(src_mp3);
else
playRaw(src_mp3);
});
function supportAudioHtml5(){
var audioTag = document.createElement('audio');
try {
return ( !!(audioTag.canPlayType)
&& (audioTag.canPlayType("audio/mpeg") != "no" && audioTag.canPlayType("audio/mpeg") != "" ) );
} catch(e){
return false;
}
}
function supportAudioFlash() {
var flashinstalled = 0;
var flashversion = 0;
if (navigator.plugins && navigator.plugins.length){
x = navigator.plugins["Shockwave Flash"];
if (x){
flashinstalled = 2;
if (x.description) {
y = x.description;
flashversion = y.charAt(y.indexOf('.')-1);
}
} else {
flashinstalled = 1;
}
if (navigator.plugins["Shockwave Flash 2.0"]){
flashinstalled = 2;
flashversion = 2;
}
} else if (navigator.mimeTypes && navigator.mimeTypes.length){
x = navigator.mimeTypes['application/x-shockwave-flash'];
if (x && x.enabledPlugin)
flashinstalled = 2;
else
flashinstalled = 1;
} else {
for(var i=7; i>0; i--){
flashVersion = 0;
try{
var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
flashVersion = i;
return (flashVersion > 0);
} catch(e){}
}
}
return (flashinstalled > 0);
}
function playHtml5(src_mp3) {
alert('html5');
if(audio != null){
if(!audio.ended){
audio.pause();
if(audio.currentTime > 0) audio.currentTime = 0;
}
}
//use appropriate source
audio = new Audio("");
if (audio.canPlayType("audio/mpeg") != "no" && audio.canPlayType("audio/mpeg") != "")
audio = new Audio(src_mp3);
//play
audio.addEventListener("error", function(e){alert("Apologies, the sound is not available.");});
alert('will play');
audio.play();
}
The last alert sentence alert('will play'); showed but I could not hear anything. However,when I clicked the audio icon directly in the CefSharp browser, it could play the pronounce. How could I fix this problem? I am not a native English speaker, I hope you can understand me. Many thanks!
[1]: https://www.ldoceonline.com/dictionary/love
This problem occured beacause Google had changed autoplay policy for audios and videos. You can active auto play by adding a commandline flag --autoplay-policy=no-user-gesture-required. In my case:
public BrowserForm()
{
InitializeComponent();
var settings = new CefSettings();
settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";//Add this statement solve the problem
Cef.Initialize(settings);
//some other statements
}
If anyone happens to meet the same problem in the futrue, I hope this will help you!
Here is a related topic.
It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.
But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.
You can use jquery to solve as I am already using it.
Thank you in advance.
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
I have edited my answer.
The button to start the timer will allow the sound to be played on safari mobile
The timer doesn't re-declare variables and functions like it did before
You could make it cleaner with less global variables but I don't know how the rest of your code would be affected by this so I didn't change it.
<button onclick=start()>start</button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script> <audio id = "songOne" src = "http://www.sousound.com/music/healing/healing_01.mp3" preload = "auto" > </audio>
<script>
// declaring variables
var betNo = 0 ;
var myAudio = document . getElementById ( 'songOne' );
var isPlaying =false;
var togglePlay=function(){
if (isPlaying) {
myAudio . pause (); }
else {
myAudio . play (); } };
myAudio . onplaying = function () { isPlaying = true ;};
myAudio . onpause = function () { isPlaying = false ;};
var start=function(){
// setTimer with only the necessary code inside so variables are not being declared more than once
boxTimer = setInterval ( function (){ if (( betNo == 0 )||( betNo == 10 )){
togglePlay (betNo); }
console . log ( betNo );
betNo ++; if ( betNo >= 20 ){
clearInterval ( boxTimer ); } }, 1000 ); }
</script>
The solution is much simpler (cause was just a silly mistake). Thanks #Rory McCrossan for pointing that out in the comments.
I just took the var isPlaying = false; out of the setInterval function, otherwise it was being set to false even if the song was playing.
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var isPlaying = false;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
document.addEventListener('DOMContentLoaded', function(event) {
var betNo = 0;
var boxTimer = setInterval(function() {
var myAudio = document.getElementById('songOne');
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause();
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
if ((betNo == 0) || (betNo == 10)) {
togglePlay();
}
console.log(betNo);
betNo++;
if (betNo >= 20) {
clearInterval(boxTimer);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}
I'm facing an issue with Java Script.
I have a piece of code that creates rain inside a div and I need this rain to turn off and on according to my if statements.
Here is that JS code that makes rain work.
var nbDrop = 120;
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
for( i=1;i<nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
So further I have a series of if statements and I want to change nbDrop variable which controls a number of drops. I want only one condition to result in raining, while others should set it to 0 value.
function displayAnswer(answer) {
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0){
nbDrop = 0;
}
else if (chosenAnswer == 1){
nbDrop = 0;
}
else if (chosenAnswer == 2){
nbDrop = 0;
}
else if (chosenAnswer == 3){
nbDrop = 0;
}
else if (chosenAnswer == 4){
nbDrop = 0;
}
else if (chosenAnswer == 5){
var nbDrop = 120;
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
for( i=1;i<nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
}
}
A problem is that it only works once when the last if statement is true. But when other conditions are true, rain keeps going, so that variable doesn't change to 0 for some reason. It stays at 120.
Even though the button I use to click to change if statements condition has an even listener on it:
<button id="button1" onclick="displayAnswer();"></button>
Is there any way to make that nbDrop variable change to zero for all other if conditions, except one which should have it set to 120?
1: You should remove the "var" in condition == 5, as it is already declared.
else if (chosenAnswer == 5){
// var nbDrop = 120;
nbDrop = 120;
2: The commented method will not run when the nbDrop is 0 as i start on 1 and 1 can never be smaller than 0
function createRain() {
// for( i=1;i<nbDrop;i++) {
for( i=0;i<=nbDrop;i++) { // need to be like this
3: You have the } sign in a wrong place. Change it like this (see the "added" and "remove" comments in the code) or the "createRain" only gets called when condition == 5 is met. If you indent your code like below you will easier see within which code block things is.
Update Added an exit part in the "createRain" function
function displayAnswer(answer) {
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0){
nbDrop = 0;
}
else if (chosenAnswer == 1){
nbDrop = 0;
}
else if (chosenAnswer == 2){
nbDrop = 0;
}
else if (chosenAnswer == 3){
nbDrop = 0;
}
else if (chosenAnswer == 4){
nbDrop = 0;
}
else if (chosenAnswer == 5){
nbDrop = 120;
} // added
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
if (nbDrop == 0) {
// remove the drop element(s)
$('.rain').children().remove();
// exit the function
return;
}
for( i=0;i<=nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
//} removed
}
And, as requested, here is the fully working web page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Magic 8 Ball</title>
<link rel="stylesheet" type="text/css" href="index.css" />
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<div id="topmask"></div>
<div id="mainframe">
<div id="mainframe2">
<section class="rain"></section>
<div id="rocketdear"></div><div id="smokedear"></div><div id="launchsmokedear"></div>
</div>
<div id="bubble"></div>
<div id="bubbleHugecat"></div><div id="bubbleHugecatrays"></div>
<div class="sign">
<p id="question"></p>
<p id="answer"></p>
</div>
<div id="eight-ball">
<button id="button1" onclick="javascript:shake();"></button>
</div>
</div>
<div id="bottommask"></div>
<script>
var nbDrop;
function shake() {
var answersArrayed = ["Yes. So nothing happens", "No. Enjoy your consequences", "Ok, but that's something different", "My answer won't help you, deal with it!", "Your questions don't matter anymore", "Your questions make it rain again"];
// The question we asked
var question = prompt("Ask you question...");
var questionText = document.getElementById('question');
questionText.innerHTML = question;
// Number of possible answers
var numberOfAnswers = answersArrayed.length;
// Answers the 8 Ball can return
// Answer returned by our 8 Ball
var chosenAnswer = getAnswerNumber(numberOfAnswers);
displayAnswer(chosenAnswer);
// Returns a number based on the number of sides
function getAnswerNumber(answerCount) {
var number = getRandomInt(0, numberOfAnswers);
return number;
}
// Returns a random integer between two numbers
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// Show our answer in the document
function displayAnswer(answer) {
}
// Access the DOM element we want to to change
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0) {
document.getElementById("bubble").className = "bubbleStill";
fortuneText.innerHTML = answersArrayed[0];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("bubble").style.opacity = "0";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 1) {
fortuneText.innerHTML = answersArrayed[1];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").className = "bubbleExploading";
document.getElementById("bubble").style.webkitAnimation = '';
document.getElementById("bubble").style.opacity = "1";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 2) {
fortuneText.innerHTML = answersArrayed[2];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("bubbleHugecatrays").style.opacity = "1";
document.getElementById("bubbleHugecat").style.opacity = "1";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 3) {
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
fortuneText.innerHTML = answersArrayed[3];
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert_night.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 4) {
fortuneText.innerHTML = answersArrayed[4];
document.getElementById("smokedear").style.opacity = "1";
document.getElementById("launchsmokedear").style.opacity = "1";
document.getElementById("rocketdear").style.opacity = "1";
document.getElementById("smokedear").className = "smoke";
document.getElementById("launchsmokedear").className = "launchsmoke";
document.getElementById("rocketdear").className = "rocket";
document.getElementById("smokedear").style.webkitAnimation = '';
document.getElementById("launchsmokedear").style.webkitAnimation = '';
document.getElementById("rocketdear").style.webkitAnimation = '';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
nbDrop = 0;
}
else {
fortuneText.innerHTML = answersArrayed[5];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
document.getElementById("mainframe").style.backgroundImage = "url('desert_rain.svg')";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
nbDrop = 120;
}
// function to generate a random number range.
function randRange(minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
if (nbDrop == 0) {
// remove the drop element(s)
$('.rain').children().remove();
// exit the function
return;
}
for (i = 0; i <= nbDrop; i++) {
var dropLeft = randRange(0, 1280);
var dropTop = randRange(-500, 590);
$('.rain').append('<div class="drop" id="drop' + i + '"></div>');
$('#drop' + i).css('left', dropLeft);
$('#drop' + i).css('top', dropTop);
}
}
createRain();
}
</script>
</body>
</html>
I am trying to add +1 to the win counter every time a win occurs but it doesn't work no matter what I try.
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="center">
<button onclick="myFunction1()">Play</button>
<p id="rolled">You rolled:</p>
<p id="test"></p>
<p id="rolled1">Your opponent rolled:</p>
<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<br><br><br>
<span>Wins:</span><span id="span1"></span><br>
<span>Losses:</span><span id="span2"></span><br>
<span>Draws:</span><span id="span3"></span>
</div>
</body>
</html>
Javascript:
var things = [ 'rock', 'paper', 'scissors'];
function myFunction1() {
var random1 = Math.floor((Math.random()*things.length));
var random2 = Math.floor((Math.random()*things.length));
document.getElementById("test").innerHTML=things[random1];
document.getElementById("test1").innerHTML=things[random2];
document.getElementById("test2").innerHTML='';
document.getElementById("test3").innerHTML='';
document.getElementById("span1").innerHTML=win;
document.getElementById("span2").innerHTML=loss;
document.getElementById("span3").innerHTML=draw;
if (random1 == random2) {
document.getElementById("test2").innerHTML="<h3>It's a draw.</h3>";
}
else if (random1 == 0 && random2 == 2) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 1 && random2 == 0) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 2 && random2 == 1) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 0 && random2 == 1) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 1 && random2 == 2) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 2 && random2 == 0) {
document.getElementById("test3").innerHTML="You lost!";
}
var test3 = document.getElementById("test3");
var win = 0;
var loss = 0;
var draw = 0;
Here is where I want to add +1 to the win counter every time a win occurs, but I can't get it to work. I have tried this:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win + 1;
}
This:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win++;
}
And this:
if (test3.innerHTML == "You win!") {
win = win + 1;
}
} //End of myFunction1
What am I doing wrong exactly?
You did not declare the variable outside the function, Declare the win variable outside the function with 0 default value. eg:-
var win = 0;
function myFunction1() {
if (test3.innerHTML == "You win!") {
win = win + 1;
....
UPDATE
Here is the fixed version DEMO
Define var win=0; outside of your function, as it is now your win variable is being created in the function and dying at the end of the function.
Another thing that you can do is: inside the function add this at the top:
var win=parseInt(document.getElementById('span1').innerText);
is test3 defined?
if (test3.innerHTML == "You win!") {
}
if not, use
if (document.getElementById("test3").innerHTML == "You win!") {
}