Displaying an average of two variables - javascript

I'm having trouble displaying the average number of clicks per round a user does for a challenge. When I go into the console I am able to calculate the average number, but I can't seem to figure out how to get it to display.
JFiddle:
https://jsfiddle.net/tglas/tkL4p8on/5/
My CSS:
<div>
round:<span id="rounds">1</span>
</div>
<div >
clicks:<span id="clicks">0</span>
</div>
<div>
Average:<span id="avgDisplay">0</span>
</div>
<button id="reset">
New Round
</button>
<button id="option1">
Option 1
</button>
<button id="option2">
Option 2
</button>
And JS:
var roundsDisplay = document.querySelector("#rounds");
var clicksDisplay = document.querySelector("#clicks");
var option1 = document.querySelector("#option1")
var option2 = document.querySelector("#option2");
var reset = document.querySelector("#reset")
var rounds = 1;
var clicks = 0;
var avg = clicks / rounds;
option1.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
})
option2.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
})
reset.addEventListener("click", function() {
rounds++;
roundsDisplay.innerHTML = rounds;
})
avgDisplay.innerHTML = avg;
I know I am probably missing something fundamental here, but I'm new to programming and would appreciate any help figuring out this concept.

You're just calculating the average one time, the first time your JS file runs. But you want to calculate the average every time you increase the counter.
Just create a function that calculates the average value every time a button is pressed and create a avgDisplay variable. (Like Olivier mentioned in the comments)
var avgDisplay = document.querySelector("#avgDisplay");
function updateAverage() {
avgDisplay.innerHTML = clicks / rounds;
}
and add it to your event callbacks after you've increased the counter
e.g.
option2.addEventListener("click", function() {
clicks++;
clicksDisplay.innerHTML = clicks;
updateAverage();
})

Related

Cannot change default value of number input in Javascript

I am using Javascript (not familiar with frameworks like Angular just yet), and trying to get and display the value of a number input from my HTML, but when I run the function that does this, the default value of "1" from the HTML seems to be the only one used, even if I change the input on the website itself to, say, 10 by clicking the arrows.
I think I've written the code correctly as far as syntax goes, so my only thought is that perhaps the input has to be wrapped in a form of some kind, and the "roll" button changed to type="submit"?
Here is a link to a codepen with the broken code, and some snippets of the involved pieces below.
var displayScreen = document.getElementById("display-message");
var rollButton = document.getElementById("roll-button");
//Variable to tell the rollDice() function how many times to roll dice.
var numDice = document.getElementById("num-dice").value;
//Dice Array to hold the results of the rollDice() function, gets cleared after each use.
var diceTotal = [];
//Event listener for the "roll" button
rollButton.addEventListener("click", rollDice);
//Make this function display a roll result
function displayMessage() {
displayScreen.innerText = diceTotal[0];
}
//Generate a random number between 1 and diceType, and set the rolledNumber variable to its result
function rollDice() {
//Nothing currently changes numDice, so it keeps default value="1".
result = 0;
var roll = Math.floor(Math.random() * diceType) + 1;
for (var i = 0; i < numDice; i++) {
result += roll;
}
diceTotal[0] = result;
displayMessage();
}
<div id="dice-display-div">
<!--
We want to display the dice roll total, any applied bonuses, and then the final total
together in this div, possibly as separate <h2> elements.
-->
<h2 id="display-message">Click "Roll" to Begin</h2>
</div>
<div id="roll-button-div">
<label class="roll-button-label" for="num-dice" id="num-dice-label">Number of Dice: </label>
<input class="roll-button-item" type="number" id="num-dice" name="num-dice" value="1" min="1" max="10">
<label class="roll-button-label" for="bonus" id="bonus-label">Bonus (or Negative): </label>
<input class="roll-button-item" type="number" id="bonus" name="bonus" value="0" min="-10" max="10">
<button class="roll-button-item" id="roll-button">Roll</button>
</div>
First, you should call your Math.random() inside the for loop, otherwise you will only randomly generate one number, and all your dice will have that same number. Second, you should assign numDice inside your function so it rechecks and assigns the current value instead of at the start of page render:
var displayScreen = document.getElementById("display-message");
var rollButton = document.getElementById("roll-button");
//Dice Array to hold the results of the rollDice() function, gets cleared after each use.
var diceTotal = [];
//Event listener for the "roll" button
rollButton.addEventListener("click", rollDice);
//Make this function display a roll result
function displayMessage() {
displayScreen.innerText = diceTotal[0];
}
//Generate a random number between 1 and diceType, and set the rolledNumber variable to its result
function rollDice() {
//Variable to tell the rollDice() function how many times to roll dice.
var numDice = document.getElementById("num-dice").value; //assign this upon function call so it checks it each time the button is clicked to get the latest value
//Nothing currently changes numDice, so it keeps default value="1".
result = 0;
var roll = 0
for (var i = 0; i < numDice; i++) {
roll = Math.floor(Math.random() * diceType) + 1; //call random on each dice roll
result += roll;
}
diceTotal[0] = result;
displayMessage();
}

Novice trying to make pagination in JavaScript

Trying to make it so this counter with buttons increases or decreases based on clicks, however on the first click the counter doesn't increase. If I do + 1 it will but then will stop. ++works but only after first click. Trying to learn easy way to resolve my code that isn't a drastic change.
https://jsfiddle.net/sy0ohtrc/
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.innerHTML = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
var elPageIncrease = document.getElementById("currentPage");
elPageIncrease.innerHTML = pageCount++;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
var elPageDecrease = document.getElementById("currentPage");
elPageDecrease.innerHTML = pageCount--;
}
You should use --/++ before the counter because when you use the increment/decrement operator after, the value will be returned before the it increased/decreased.
AND there is no need for declaring 3 time the same element.
Finally change the innerHTML to textContent (and if you want to know why read this thread).
Your code should look something like that:
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.textContent = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
// var elPageIncrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = ++pageCount;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
// var elPageDecrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = --pageCount;
}
<div class="pager">
<button id="prevButton">prev</button>
<p class="pageNumber" id="currentPage"></p>
<button id="nextButton">next</button>
</div>

How to show only selected number of elements in array?

I developed a party-game just for fun, and can't solve this problem. So, at first I ask user "How many clothes you want to see?". I set that data to local storage, and use on other page. So my problem is: I want to show only user selected number of elements in array (I'm so sorry for my bad english, I really need your help). Here are my codes:
index.html
<div class="container">
<div class="small-container">
<p id="text">How many clothes you want to choose ?</p>
<input type="number" placeholder="1 to 6" id="count" />
</div>
<button id="btn">Start</button>
</div>
script1.js
window.onload = function() {
var btn = document.getElementById("btn");
var count = document.getElementById("count");
btn.addEventListener("click", function() {
document.location.href = "random.html";
localStorage.setItem("count", count.value);
});
};
game.html
<div class="small-container">
<p id="text">Your random clothes: </p>
<img id="img" />
</div>
script2.js
var options = [
"T-Shirt",
"Singlet",
"Underwear",
"Socks",
"Shorts",
"Shoes"
];
var btn = document.getElementById("btn");
var text = document.getElementById("text");
var img = document.getElementById("img");
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
if (randomChoice >= options.length) {
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
});
};
So every time user clicks the button, clothes are changing. For example, if user was chosen 4 as count, I want to show him/her only 4 clothes, and they must see before every click just one image on their pages.
If i understood ur question correctly, your issue was that you didnt know how to stop the game once the good amount of clothes has been shown
Here is a solution
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
localStorage.setItem("count", count-1); //decreasing the value of count because one clothe is about to be shown on screen
if (count == 0) { //if count is at 0, that means game is over
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
else{ //we show a new cloth
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
}
});
But with that code its still possible that the same cloth is picked several times.
To avoid that, while keeping the code in pure javascript, I guess you could use "hidden" inputs to store the clothes that have been shown, or other localStorage variables.

click 2 times show text javascript

I am writing a little clicking game with javascript at the moment and I am currently stuck with a little challenge. I need it so that whenever i have clicked a button 10 times. my second value should increase by one. Maybe a little bit hard to understand, I'll try to explain it in code.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
Amount = 0;
// Whenever I click the button..The Amount increases like this.
Amount++;
// so after one click the amount should be..
Amount = 1;
// I need it so that when the button has been clicked 10 times I want to display //that. Something like this.
timesThatTheButtonHasBeenClickedTenTimes = 1;
Should I do this with a while loop or what.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
var amount = 0;
var counter = function () {
amount++;
if (amount === 10) {
amount = 0;
timesThatTheButtonHasBeenClickedTenTimes++;
}
document.getElementById('clicks').innerHTML = amount;
document.getElementById('hits').innerHTML = timesThatTheButtonHasBeenClickedTenTimes;
};
document.getElementById("mybutton").addEventListener("click", counter);
<button id='mybutton'>
Click me!
</button>
<p>
Clicks = <span id='clicks'>0</span>
</p>
<p>
10 times hits = <span id='hits'>0</span>
</p>
Hope it helps!
You could do something like:
var timesButtonClicked = 0;
var secondValue = 0;
if (timesButtonClicked === 10) {
secondValue++;
timesButtonClicked = 0;
} else {
timesButtonClicked++;
}
This is the very simple solution for you problem:
var clicks = 0;
Clicker = function() {
clicks++;
console.log('You clicked '+clicks+' times already.');
if(clicks == 10){
alert('Something what you want to alert.')
clicks = 0;
}
}
<button onclick="Clicker()">
Click me 10x times pls
</button>
One approach I'd suggest is:
function increment() {
// find the current number of times the <button> has been clicked,
// if the <button> has a data-current attribute we retrieve that
// attribute-value and parse it as a number in decimal format;
// if it does not have that custom data-* attribute we set the
// variable to 0:
let currentValue = this.dataset.current ? parseInt(this.dataset.current, 10) : 0;
// here we update the data-current attribute to the incremented value
// of the currentValue:
this.dataset.current = ++currentValue;
// we retrieve the element with the id of 'clicks', and set
// its textContent to the value held by the currentValue:
document.getElementById('clicks').textContent = currentValue;
// here we retrieve the element with an id of 'numberOfTens',
// and set its textContent to the floored value of the currentValue
// divided by 10:
document.getElementById('numberOfTens').textContent = Math.floor(currentValue / 10);
}
// here we retrieve the element with the id of 'clicker':
document.getElementById('clicker')
// and bind the increment() function (note the deliberate lack of
// parentheses) as the event-handler for the 'click' event:
.addEventListener('click', increment);
div:empty::before {
content: '0';
}
#clicks::after {
content: ' clicks.';
}
#numberOfTens::after {
content: ' tens of clicks.';
}
<button id="clicker">Click</button>
<div id="clicks"></div>
<div id="numberOfTens"></div>
References:
CSS:
:empty pseudo-class.
Pseudo-elements, ::before, ::after.
content property.
JavaScript:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.
parseInt.
Pre-increment variable ++variableName.

Click Counter not working

This is a super basic counter which just counts the button clicks. Below is the body of my html.
<body>
<div class="wrapper" ><button id="but"> Click</button></div>
<h2><div class="counter"> Counter: <span id = "countNum"> 0 </span></div></h2>
<script type="text/javascript">
var button = document.getElementById('but');
var counter = document.getElementbyId('countNum');
var count = 0;
button.onClick = function() {
count += 1;
counter.innerHTML = count;
};
</script>
</body>
However, there is simply no change on my counter when I click the button. I've tried placing output statements in the start of the script but they don't show up either. Have I placed it wrong? Is it an error with my code?
I've gone through all the similar posts but cannot figure out my error.
You misspelled quite a few functions here.
Here is the correct javascript code.
Please note that its case sensitive, i.e. document.getElementbyId is not the same as document.getElementById, and button.onClick is not the same as button.onclick.
var button = document.getElementById('but');
var counter = document.getElementById('countNum');
var count = 0;
button.onclick = function() {
count += 1;
counter.innerHTML = count;
};

Categories