Create Reset button for a counter - javascript

I have this counter. It is a counter that uses Javascript Closure. Can you help me with a reset button?
If you can, to this type of "counter" code, not to another...
HTML CODE
<button type="button" onclick="geo()">Count!</button>
<p id="count">0</p>
JAVASCRIPT CODE
<script>
var count= (function () {
var nr = 0;
return function () {nr+= 1; return nr;}
})();
function geo(){
document.getElementById("count").innerHTML = count();
}
</script>

I'm not even sure what you have right now is working.
const addBtn = document.querySelector('#add');
const resetBtn = document.querySelector('#reset');
const pCount = document.querySelector('#count')
let start = 0;
function add(){
start++
pCount.innerHTML = start
}
function reset(){
start = 0;
pCount.innerHTML = start
}
addBtn.addEventListener('click', add)
resetBtn.addEventListener('click', reset)
<button id="add"> Add </button>
<button id="reset" > Reset </button>
<p id="count"></p>

I don't know much about the closure (seems very interesting...) but moving nr variable outside of your function and then call a reset on nr will reset the counter.
var count = (function() {
var nr = 0;
return function(reset = false) {
nr = reset ? 0 : nr + 1
return nr;
}
})();
function geo() {
document.getElementById("count").innerHTML = count();
}
function reset() {
document.getElementById("count").innerHTML = count(true);
}
<button type="button" onclick="geo()">Count!</button>
<button type="button" onclick="reset()">Reset!</button>
<p id="count">0</p>

Related

my code is about to increment the counter in the browser when we click in the increment button

when we click on the increment button the counter shows in the browser not incrementing.
let countEl = document.getElementById("count-el");
console.log(countEl);
let count = 0;
function increment() {
count = count + 1;
countEl.innertext = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
function increment() {
let countEl = document.getElementById("count-el");
let count = countEl.innerHTML;
console.log(count);
count++;
countEl.innerHTML = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
Javascript is case-sensitive. in your code you wrote
.innertext = ...
which should have been
.innerText = ...
Also, it is better to attach event click on the button rather on rely on onclick since you can't guarantee if the script file has already been loaded or not.
let countEl = document.getElementById("count-el");
console.log(countEl);
let count = 0;
let button = document.getElementById("increment-btn");
button.addEventListener('click', increment);
function increment() {
count = count + 1;
countEl.innerText = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" >INCREMENT</button>

use location.hash to keep page status in javascript

I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

javascript counter is not increasing counter in each call

In the javascript code i was expecting that this function should increment the counter each time it is called but the value is remaining same for each time it is called, that is 1.. why is it not incrementing.
<body>
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
<script>
function add(){
var counter = 0;
return counter = counter + 1;
}
</script>
</body>
Define counter globally(outside the function) or else every time when function is being called, value of counter is set to 0
var counter = 0;
function add() {
return counter = counter + 1; //OR return ++counter;
}
<p>increasing the counter</p>
<button type="button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id="para"></p>
You need to take your counter variable outside your function definition( i.e. define it as a global variable ), so that it retains its previous value. Otherwise every time you call the function, its value is reset to 0.
<body>
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
<script>
var counter = 0;
function add(){
return counter = counter + 1;
}
</script>
</body>
counter is set back to 0 in each call.
In this case counter could just be moved outside of the function:
var counter = 0;
function add(){
return counter = counter + 1;
}
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
Slightly alter program
<html>
<body>
<script>
var counter = 0;
function add() {
return counter = counter + 1;
}
</script>
<p>increasing the counter</p>
<button type="button" onclick="document.getElementById('para').innerHTML = add
()">Counter</button>
<p id="para"></p>
</body>
</html>
Declare counter out of the add() function. Every time add() is invoked the counter is set to ZERO counter = 0 and then it is returned after incrementing by 1 return counter = counter + 1.
var counter = 0;
function add (){
return counter = counter + 1;
}
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
Second Method, if you want to declare var counter in add() (to avoid polluting global scope ) use JS closure. See following code snippet.
var add = (function (){
var counter = 0;
return function() {return counter = counter + 1;}
})();
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>

Adding scores to a variable

I am new to coding and I have completed Codecademy's HTML, CSS and Javascript courses, and now I am making a very simple game.
I am trying to add 5 to my variable score, but I don't know how! I can use ++score to add 1, but I don't know how to add 5.
My simplified code for adding 1 is:
<html>
<head>
<title>Webpage</title>
<script>
var score = 0;
function add1() {
alert("Adding +1 to your score!");
++score;
alert(score);
};
</script>
</head>
<body>
<button onclick="add1()";> Add One </button>
</body>
</html>
shortest / easiest + 5 in Javascript
score += 5;
add + 5 to the score and set that as the score
score = score + 5;
function add1() {
alert("Adding +5 to your score!");
score = score + 5;
alert(score);
};
You can add this in.It's like the web storage Api if you disable the alert.Learn more
var score = 0;
document.getElementById("boy").innerHTML = +score;
function correct() {
alert("And that is correct!")
++score;
document.getElementById("boy").innerHTML = +score;
return true;
}
function wrong() {
alert("And that is wrong!")
return false;
}
var times = 0;
document.getElementById("hey").innerHTML = +score;
function yourname() {
++times;
document.getElementById("hey").innerHTML = +times;
}
<p>
Score:<span id="boy"></span>
</p>
<h2>Is javascript powerful?</h2>
<button onclick='correct()'>Yes</button>
<button onclick='wrong()'>No</button>
<h2>If you went into the w3schools link.This feels familar.</h2>
<p>
You have clicked the button:<span id="hey"></span> times
</p>
<button onclick="yourname()">Click me!!!</button>
You maybe will not see the snippet.
Javascript:
var score = 0;
document.getElementById("boy").innerHTML = +score;
function correct() {
alert("And that is correct!")
++score;
document.getElementById("boy").innerHTML = +score;
return true;
}
function wrong() {
alert("And that is wrong!")
return false;
}
var times = 0;
document.getElementById("hey").innerHTML = +score;
function yourname() {
++times;
document.getElementById("hey").innerHTML = +times;
}
Html:
<p>
Score:<span id="boy"></span>
</p>
<h2>Is javascript powerful?</h2>
<button onclick='correct()'>Yes</button>
<button onclick='wrong()'>No</button>
<h2>If you went into the w3schools link.This feels familar.</h2>
<p>
You have clicked the button:<span id="hey"></span> times
</p>
<button onclick="yourname()">Click me!!!</button>

Categories

Resources