Passing variables from JavaScript to HTML and HTML button inputs to JavaScript - javascript

I am trying to make a simple game using JavaScript and HTML.
The game consists of having two buttons on the screen with random numbers and clicking the one that is smaller.
At the end, you will get your results.
What I am having trouble with is getting the random number generated in JavaScript to print on the button and getting the data back to JavaScript from the button.
var number = prompt('Choose Your Difficulty, Easy, Normal, Or Hard?');
var number = number.toUpperCase(); //Chooses difficulty
if (number === 'EASY')//easy difficulty
{
var difficulty = 20;
}else if (number === 'NORMAL')//normal difficulty
{
var difficulty = 100;
}else if(number === 'HARD')//hard difficulty
{
var difficulty = 1000;
}else
{
alert('Please Enter A Valid Answer')//if value is not valid
}
var number1 = Math.floor((Math.random()* difficulty) + 1);//random number 1
var number2 = Math.floor((Math.random()* difficulty) + 1);//random number 2
//----------------------Code i found but im not sure now to use it--------------
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener("click", function() {
alert("did something");
});
//-----------------------------------------------------------------------------
button {
margin-top: 20px;
line-height: 60px;
font-weight: bold;
padding: 0 40px;
background: salmon;
border: none;
}
button:hover {
background: lightsalmon;
}
<!DOCTYPE html>
<html>
<head>
<title>
Speed Game
</title>
<link href="css/styles.css" rel="stylesheet"
type="text/css">
<script src="../script/script.js"></script>
</head>
<body>
<button id= "button">
Do Something!
</button>
</body>
</html>
How can I solve this problem?

First of all, welcome to the world of programming!
Second, here's the game you wanted. I've done everything using functions, so understanding it should be easy.
Try to play a few games first!
The concept is pretty simple, really, so after playing a bit, look at the code and try to figure it out on your own!
var number;
var difficulty = 0;
var randomNumOne;
var randomNumTwo;
var buttonOne = document.getElementById("buttonOne");
var buttonTwo = document.getElementById("buttonTwo");
var tempButton;
function requestDifficulty(){
number = prompt('Choose Your Difficulty, Easy, Normal, Or Hard?');
number = number.toUpperCase();
setDifficulty();
}
function setDifficulty(){
if (number === 'EASY'){
difficulty = 20;
startGame();
}else if (number === 'NORMAL'){
difficulty = 100;
startGame();
}else if(number === 'HARD'){
difficulty = 1000;
startGame();
}else{
alert('Please Enter A Valid Answer');
requestDifficulty()
}
}
function startGame(){
randomNumOne = Math.floor((Math.random()* difficulty) + 1);
randomNumTwo = Math.floor((Math.random()* difficulty) + 1);
buttonOne.innerHTML = randomNumOne;
buttonTwo.innerHTML = randomNumTwo;
}
function getResults(pressedButton){
tempButton = pressedButton;
if(tempButton == "buttonOne"){
if(randomNumOne < randomNumTwo){
alert("Correct!")
}else{
alert("False!")
}
}else if(tempButton == "buttonTwo"){
if(randomNumTwo < randomNumOne){
alert("Correct!")
}else{
alert("False!")
}
}
}
requestDifficulty();
button {
margin-top: 20px;
line-height: 60px;
font-weight: bold;
padding: 0 40px;
background: salmon;
border: none;
}
button:hover {
background: lightsalmon;
}
<!DOCTYPE html>
<html>
<head>
<title>
Speed Game
</title>
</head>
<body>
<button id="buttonOne" onclick="getResults('buttonOne');">
random number 1
</button>
<button id="buttonTwo" onclick="getResults('buttonTwo')">
random number 2
</button>
</body>
</html>

Related

Lottery game - Not allowed to input the same number twice - JS

I am very new to javaScript and I am currently trying to code a Lottery Game. The User is allowed to input 6 numbers between 1 and 49 and then Generate 6 random numbers and it will then tell you how many Numbers you got correct.
Everything seems to be working great so far but i can not figure out how to Code that you
Can not input the same number twice (This should result in an error code)
The Randomizer isnt allowed to draw the same number twice
My Code looks like this so far:
function validateBall(num) {
let ballValue = document.getElementById("ball" + num).value;
if (ballValue == "") {
alert("Ball " + num + " braucht eine Zahl");
return false;
}
if (isNaN(ballValue)) {
alert("Ball " + num + " ist keine Zahl");
return false;
}
let numberValue = parseInt(ballValue);
if (numberValue <= 0 || numberValue > 49) {
alert("Die Zahl des Balls muss zwischen 1-49 liegen");
return false;
}
return numberValue;
}
function containsDuplicates(ballValue) {
return array.length !== new Set(ballValue).size;
}
function output(str) {
let output = document.getElementById("output");
var tag = document.createElement("p");
var text = document.createTextNode(str);
tag.appendChild(text);
output.appendChild(tag);
}
function Jetzt_Spielen() {
let value1 = validateBall("1");
if (value1 == false)
return;
let value2 = validateBall("2");
if (value2 == false)
return;
let value3 = validateBall("3");
if (value3 == false)
return;
let value4 = validateBall("4");
if (value4 == false)
return;
let value5 = validateBall("5");
if (value5 == false)
return;
let value6 = validateBall("6");
if (value6 == false)
return;
let values = [value1, value2, value3, value4, value5, value6];
let outputDiv = document.getElementById("output");
outputDiv.innerHTML = "";
let matched = 0;
for (let i = 0; i < 6; i++) {
let randomNumber = Math.round(1 + Math.random() * 48);
output("Gezogene Zahl: " + randomNumber);
for (let j = 0; j < 6; j++) {
let myBallValue = values[j];
if (randomNumber == myBallValue) {
matched++;
break;
}
}
}
output("Du hast " + matched + " richtige Zahl(en)")
}
<div class="gelbe_box">
<h1>Lotto 6aus49</h1>
</div> <br>
<div class="position_middle">
<input id="ball1" class="LottoZahlen" />
<input id="ball2" class="LottoZahlen" />
<input id="ball3" class="LottoZahlen" />
<input id="ball4" class="LottoZahlen" />
<input id="ball5" class="LottoZahlen" />
<input id="ball6" class="LottoZahlen" />
<button id="submitBtn" value="button" onclick=" Jetzt_Spielen();">Jetzt Spielen</button>
<div id="output">
</div>
I dont really know how to continue with this. I either did something wrong already that I cant do it with this code or I just can not figure the code(s) out..
I'd really appreciate some help!!
Thank you in advance :)
Good UX and Restrictions
Plan the layout (HTML and essential CSS) first. To control how interaction with the user is done relies heavily on HTML and CSS, JavaScript is used to facilitate this interaction, gather user data, and process user's data and/or new data. In order to answer your question, I'm compelled to show you an approach to meet your objective and provide a solution that's foolproof for your particular problem.
HTML
If you require interaction from a user use a <form> and keep all of your relevant layout inside of it. Present only what the user needs to use, ideally a single form control like a button. Hide the rest of the HTML and restrict the user to go through phases. Instruct the user with simple messages and visual prompts. Don't use prompt() (it's aesthetically unappealing and popups feel "rude" IMO):
Figure I - The Layout
<form id='lottery'><!-- Wrap <form> around everything -->
<fieldset id='box'>
<!-- Always have simple clear directions -->
<legend>Click the button to begin</legend>
<!-- Offer the user only one or two choices at a time -->
<!-- ATM there are two empty <select> and a <button> that automatically
has focus (see Figure II). There's a <legend> prompting user to click
the <button>. There's also a hidden <button> and <output> ready for
the next phase.
-->
<select id='choices' multiple></select>
<!-- This button has focus as soon as the page is loaded because it's
assigned "tab-index='0'" and there's a line of JavaScript
(see Figure II)
-->
<button id='begin' tab-index='0'>Begin</button>
<button id='done' tab-index="0" type='button'>Done</button>
<select id='picked' multiple></select>
</fieldset>
<output id='note' class='hide'>
<small><sup>✳️</sup>To deselect a number, click the number in field on the right</small>
</output>
<!-- This hidden section is the final phase which displays the user's
numbers, the winning lottery numbers, and the numbers that matched.
-->
<fieldset id='results' class='hide'>
<label for='final'>Your Numbers: </label><output id='final' class='array'></output><br>
<label for='targets'>Winning Numbers: </label><output id='targets' class='array'></output><br>
<label for='hits'>Matching Numbers: </label><output id='hits' class='array'></output><br>
<button type='reset'>Replay</button>
</fieldset>
</form>
JavaScript
// This will hold the numbers the user picks
let numbers = [];
/*
This is an array of 49 empties "". It will be used as a counter and
then later repurposed to hold the winning numbers
*/
let A49 = [...Array(49)];
/*
Throughout this example the terse syntax of the HTMLFormsElement
interface will be used extensively. This references the <form>
*/
const lot = document.forms.lottery;
// 1st phase init(e) populates a <select> with 49 <option>s
lot.addEventListener('submit', init);
/*
2nd phase pick(e) allows the user to pick 6 numbers, no need to validate
user input there are 49 numbers and each number can only be picked once.
*/
lot.addEventListener('input', pick);
/*
Last phase draw(e) collects the users array of 6 numbers, then generates
a randomized array of 6 numbers, then displays both arrays with matches
highlighted.
*/
lot.elements.done.addEventListener('click', draw);
lot.onreset = function() {
window.location.reload();
};
lot.elements.begin.focus();
function init(e) {
e.preventDefault();
const IO = this.elements;
A49 = A49.map((_, index) => {
IO.choices.insertAdjacentHTML(
'beforeend',
`<option value="${index + 1}">${index + 1}</option>`
);
return index + 1;
});
//...
This answer is huge, apologies, I'll return later on to finish explaining the rest of this code. It's foolproof and meets if not exceeds all objectives of the OP, I hope this helps.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<style>
html {
font: 300 5vmin/1.25 'Segoe UI';
}
fieldset {
max-width: 15rem;
}
#box {
display: flex;
justify-content: center;
align-items: center;
}
input,
button,
output,
select,
label {
display: inline-block;
margin: 4px;
font: inherit;
}
button {
padding-bottom: 0.25rem;
border: 0;
border-radius: 2px;
outline: 0;
cursor: pointer;
}
label {
width: 4rem;
margin-right: 0;
}
mark {
padding: 1px;
background-color: #0047AB;
color: gold;
}
small {
font-size: 0.5rem;
}
legend b {
font-family: Consolas;
}
select {
width: 3rem;
height: 9rem;
border: 0.5 inset lightgrey;
border-radius: 2px;
outline: 0;
font-family: Consolas;
}
#choices {
overflow-y: scroll;
scrollbar-width: thin;
}
#choices::-webkit-scrollbar {
width: 0.25rem;
height: 9rem;
}
#picked {
overflow-y: hidden;
}
.array {
width: 7.5rem;
font-family: Consolas;
}
.hide {
visibility: hidden;
}
#done {
display: none;
}
#note {
margin-top: -4px;
}
[type='reset'] {
float: right;
}
select:focus,
button:focus {
color: #0047AB;
box-shadow: 0 0 0 2pt cornflowerblue;
}
</style>
</head>
<body>
<form id="lottery">
<fieldset id="box">
<legend>
Click the button to begin
</legend>
<select id="choices" multiple></select>
<button id="begin" tab-index="0">Begin</button>
<button id="done" tab-index="0" type="button">Done</button>
<select id="picked" multiple></select>
</fieldset>
<output id="note" class="hide">
<small>
<sup>✳️</sup>To deselect a number, click the number in field on the
right
</small>
</output>
<fieldset id="results" class="hide">
<label for="final">Your Numbers: </label>
<output id="final" class="array"></output><br />
<label for="targets">Winning Numbers: </label>
<output id="targets" class="array"></output><br />
<label for="hits">Matching Numbers: </label>
<output id="hits" class="array"></output><br />
<button id='replay' tab-index='0' type="reset">Replay</button>
</fieldset>
</form>
<script>
let numbers = [];
let A49 = [...Array(49)];
const lot = document.forms.lottery;
lot.addEventListener('submit', init);
lot.addEventListener('input', pick);
lot.elements.done.addEventListener('click', draw);
lot.onreset = function() {
window.location.reload();
};
lot.elements.begin.focus();
function init(e) {
e.preventDefault();
const IO = this.elements;
A49 = A49.map((_, index) => {
IO.choices.insertAdjacentHTML(
'beforeend',
`<option value="${index + 1}">${index + 1}</option>`
);
return index + 1;
});
IO.box.firstElementChild.innerHTML = `Pick <b>6</b> numbers -- 1 to 49<sup><small>✳️</small></sup>`;
IO.note.classList.remove('hide');
IO.begin.remove();
IO.done.style.display = 'inline-block';
IO.done.disabled = true;
IO.choices.focus();
}
function pick(e) {
const IO = this.elements;
const sel = e.target;
if (sel.id === 'choices') {
const copy = sel.options[sel.selectedIndex].cloneNode(true);
IO.picked.append(copy);
numbers.push(+sel.value);
sel.options[sel.selectedIndex].remove();
}
if (sel.id === 'picked') {
const copy = sel.options[sel.selectedIndex].cloneNode(true);
IO.choices.append(copy);
let nodeList = [...IO.choices.options];
let ordered = nodeList.sort((a, b) => +a.value - +b.value);
IO.choices.replaceChildren(...nodeList, ...ordered);
numbers = numbers.filter((number) => number !== +sel.value);
sel.options[sel.selectedIndex].remove();
}
if (numbers.length === 6) {
IO.choices.disabled = true;
IO.done.disabled = false;
IO.done.focus();
} else {
IO.choices.disabled = false;
IO.done.disabled = true;
}
IO.box.firstElementChild.innerHTML = `Pick <b>${
6 - numbers.length
}</b> numbers -- 1 to 49<sup><small>✳️</small></sup>`;
}
function draw(e) {
const IO = this.closest('form').elements;
IO.box.disabled = true;
IO.note.classList.add('hide');
IO.results.classList.remove('hide');
let drawn = shuffle(A49);
drawn.length = 6;
let match = drawn.filter((number) => numbers.includes(number));
IO.final.innerHTML = mark(numbers, match);
IO.targets.innerHTML = mark(drawn, match);
let outcome = match.length > 0 ? mark(match) : 'Goose Egg 🥚';
IO.hits.innerHTML = outcome;
IO.replay.focus();
}
function shuffle(array) {
let qty = array.length,
temp,
i;
while (qty) {
i = Math.floor(Math.random() * qty--);
temp = array[qty];
array[qty] = array[i];
array[i] = temp;
}
return array;
}
function mark(arrayA, arrayB = arrayA) {
arrayA.sort((a, b) => a - b);
return arrayA.map((n) =>
arrayB.includes(n) ? `<mark>${n}</mark>` : n
);
}
</script>
</body>
</html>

Ascii Art Animation in Browser

I want to animate Ascii Art in the Browser.
The Ascii Art should be loaded via a text file. There are many libraries which convert but I have found none, which actually animates it.
By animation I mean a typewriter animation that speeds up over time and changes the 'zoom factor' so that the whole image is visible in the viewport at the end.
Hopefully anyone knows a libary for my problem.
I have a feeling SO doesn't like library recommendations, and actually I haven't found one, so here's some basic code to get you started.
It sets the typing speed to the old Teletype 10 chars per second and of course that can be changed, and an acceleration function can be added when you know what you want for that. Note: the txt file needs to be on the same domain to prevent CORS problems.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typewriter print</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Courier, monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div id="container">
<input id="file" type="text" value="" placeholder="Filename" />
<button onclick="loadFile()">Click to draw the file</button>
<div id="picture"></div>
</div>
<script>
let file = '';
let reader = new XMLHttpRequest();
function loadFile() {
file = document.getElementById('file').value;
reader.open('get', file, true);
reader.onreadystatechange = draw;
reader.send(null);
}
function draw() {
if (reader.readyState == 4) {
const picture = document.getElementById('picture');
picture.innerHTML = '';
let str = reader.responseText;
let chs = str.split('');
//set as the typing speed in characters
//per second 10 is the old teletype speed
let chsPerSec = 10;
let i = 0;
function reveal() {
if (i < chs.length) {
let nextch = chs[i];
if (nextch.charCodeAt(0) == 10) {
nextch = '<br>';
} else if (nextch.charCodeAt(0) == 32) {
nextch = '<span style="color:transparent;">.</span>';
}
picture.innerHTML = picture.innerHTML + nextch;
setTimeout(reveal, Math.floor(1000 / chsPerSec));
i++;
}
}
reveal();
}
}
</script>
</body>
</html>

How React Dom update works in comparison to Vanilla JS update approach

I am a beginner in React although have worked on multiple JS frameworks like Angular. I was going through their tutorial and got stuck at a concept mentioned at below URL.
https://reactjs.org/docs/rendering-elements.html
It says -
"React DOM compares the element and its children to the previous one,
and only applies the DOM updates necessary to bring the DOM to the
desired state."
They have demonstrated it through a clock example
I was viewing a stop watch demo at following URL written in Vanilla JavaScript.
When I inspect the DOM I see similar behavior of DOM update.
Stop Watch # Codepen
I don't understand what does React do differently as highlighted by them in their child element rendering concept.
Any help will be greatly appreciated
var timing = false;
var interval;
var time = 0;
var count = document.getElementById("time");
var s = document.getElementById("s");
var r = document.getElementById("r");
var t = document.getElementById("t");
var past = document.getElementById("past");
function startstop(){
if(!timing) {
interval = setInterval(function () {
time += 0.01;
count.innerHTML = time.toFixed(2).toString();
}, 10);
timing = true;
} else {
clearInterval(interval);
timing = false;
}
}
function reset(){
clearInterval(interval);
time = 0;
count.innerHTML = "0";
timing = false;
past.innerHTML = "";
}
function record(){
var node = document.createElement("li");
var textnode=document.createTextNode(count.innerHTML);
node.appendChild(textnode);
past.appendChild(node);
}
s.addEventListener("click",startstop);//not s.addEventListener("click",startstop());
r.addEventListener("click",reset);
t.addEventListener("click",record);
document.addEventListener("keydown",function(event){
var press = event.key;
switch (press)
{
case "s" :
startstop()
break;
case "r":
reset()
break;
case "t":
record()
break;
default:
return
}
});
*{
text-align: center;
margin:20px 10px;
color:#C096E6;
}
h1{
margin-top:50px;
}
#time{
font-size:40px;
}
button{
width: 100px;
height: 100px;
color:#ffffff;
background-color: #C096E6;
border-radius: 50%;
border:none;
outline:none;
&:hover{
color: #C096E6;
background-color: #ffffff;
border: 1px solid #C096E6;
}
}
ul{
margin-left: -20px;
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game</title>
</head>
<body>
<h1>Stopwatch Demo</h1>
<p id="time">0</p>
<button id="s">Start/Stop</button>
<button id="r">Reset</button>
<button id="t">Record Time</button>
<p>Past Times</p>
<ul id="past"></ul>
</body>
</html>

Getting different id for 24 buttons, made with a for loop

I have made 24 buttons with a for loop, and want button from number 1 to 24 to give a message like this.
"you clicked on button 1"
"you clicked on button 2" and so on.
I have been able to split the 3 first buttons so they say "button 1" "2" "3", but that is done by 3 if statements, which means i would need 23-24 ish if statements to get them all to do as I want. That's not a very efficient way to do it.
Is there a good way to get the button id to add +1 after "knapp" every time the loop runs ? something like this element.id = "knapp" + 1; < so the id become knapp1, knapp2, knapp3 as the loop keep running 24 times ?
html:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<script src="Assignment06.js"></script>
<style>
h1 {
text-align: center;
}
div {
background-color: forestgreen;
border: solid 1px #000;
display: inline-block;
width: 100px;
height: 100px;
padding: 10px
}
#panel {
width: 610px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Assignment06</h1>
<p id = "panel"></p>
</body>
</html>
Javascript:
function dag(){
knapp = window.alert("Du trykket knapp 1");
}
function dag2(){
window.alert("Du trykket knapp 2");
}
function dag3(){
window.alert("Du trykket knapp 3");
}
function init(){
knapper();
}
function knapper(){
for (var antall = 1; antall <= 24; antall++){
if(antall == 1){
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp";
knapp = element.addEventListener("click", dag);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
else if (antall == 2){
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp2";
knapp2 = element.addEventListener("click", dag2);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
else{
var element = document.createElement("div");
element.innerHTML = antall;
element.id = "knapp3";
knapp3 = element.addEventListener("click", dag3);
element.type = "div";
var panel = document.getElementById("panel");
panel.appendChild(element);
}
}
}
window.onload = init;
You can save the id in the dataset of the <div /> element.
function knapper() {
var panel = document.getElementById("panel");
for (var antall = 1; antall <= 10; antall++) {
var element = document.createElement("div");
element.innerHTML = antall;
element.dataset.id = antall;
element.addEventListener("click", dag);
panel.appendChild(element);
}
}
function dag(evt) {
alert(evt.target.dataset.id);
}
window.onload = knapper;
#panel div {
width: 50px;
height: 50px;
border: solid 1px black;
float: left;
}
<div id="panel"></div>
To directly answer your question without suggestions:
You already have a counter in the for loop (antall). You can just use that variable and concatenate it on the end of the string that you're using as an id.
element.id = "knapp" + antall;

Auto-Play feature not executing in JS

I have somewhat of a baseball game, obviously there are not bases or hits. Its all stikes, balls and outs. The buttons work and the functionality of the inning (top and bottom as well as count) are working. I want this to ideally randomly throw a pitch on its own every few seconds. Basically to randomly "click" the ball or strike button. I am trying to use the setTimeout function with no success. Any help?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="bullpen.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bullpen</title>
</head>
</html>
<body>
<button id=buttons onclick="playBall()">Auto-Play</button>
<h2>Inning: <span id=inningHalf></span> <span id=inningNum></span></h2>
<div id=buttons>
<button onclick="throwBall(), newInning()">Ball</button>
<button onclick="throwStrike(), newInning()">Strike</button>
</div>
<h2>Count: <span id=ball>0</span> - <span id=strike>0</span></h2>
<h2>Outs: <span id=out>0</span></h2>
<h2>----------------</h2>
<h2>Walks: <span id=walks>0</span></h2>
<h2>Strikeouts: <span id=strikeout>0</span></h2>
<script src="bullpen.js"></script>
</body>
</html>
JS:
var ball = 0;
var strike = 0;
var out = 0;
var walks = 0;
var strikeout = 0;
//---------------------------------
var outPerInning = 0;
var inning = 1;
//---------------------------------
document.getElementById('inningNum').innerHTML = inning;
document.getElementById('inningHalf').innerHTML = '▲';
function throwBall(){
ball++;
document.getElementById('ball').innerHTML = ball;
if (ball == 4){
ball = 0;
strike = 0;
walks++;
document.getElementById('walks').innerHTML = walks;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function throwStrike(){
strike++;
document.getElementById('strike').innerHTML = strike;
if(strike == 3){
ball = 0;
strike = 0;
strikeout++;
out++;
outPerInning++;
document.getElementById('strikeout').innerHTML = strikeout;
document.getElementById('out').innerHTML = out;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function newInning(){
if(out == 3){
ball=0;
strike=0;
out=0;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
document.getElementById('out').innerHTML = 0;
}
if(outPerInning == 3){
document.getElementById('inningHalf').innerHTML = '▼';
}
if(outPerInning == 6){
inning++;
document.getElementById('inningHalf').innerHTML = '▲';
outPerInning = 0;
document.getElementById('inningNum').innerHTML = inning;
}
};
function playBall(){
var play = Math.random;
if(play >= 0.4){
throwStrike();
newInning();
}
else{
throwBall();
newInning();
}
setTimeout(playBall, 5000);
};
CSS if needed:
h2{
margin-left: 50px;
font-size: 50px;
}
button{
font-size: 45px;
}
#buttons{
width: 227px;
margin-left:50px;
margin-top: 20px;
}
Perhaps this is the problem:
function playBall(){
var play = math.random;
if(play >= 0.4){
throwStrike;
newInning();
}
else{
throwBall;
newInning();
}
setTimeout(playBall, 5000);
};
Should be
function playBall(){
var play = Math.random();
if(play >= 0.4){
throwStrike(); //call the function
newInning();
}
else{
throwBall(); //call the function
newInning();
}
setTimeout(playBall, 5000);
};
You were not calling these functions!
Here is a working fiddle: https://jsfiddle.net/av6vsp7g/

Categories

Resources