user5323957 user5323957 - 3 months ago 11
HTML Question

Reset button not resetting the value to 0

Doing a basic DOM manipulation here. Everything is working fine: when any player reaches a predefined number like 5, for now the score turns green and it stops further increment. Then, when I click the “Reset” button, it resets to “0 to 0”, but when I click any of the “Player” buttons, it continues with the previous value instead of starting from 0.

/*global prompt,alert,console*/
/*jslint plusplus: true */
var button1 = document.querySelector(".button1");
var button2 = document.querySelector(".button2");
var p1Display = document.querySelector(".p1display");
var p2Display = document.querySelector(".p2display");
var reset = document.querySelector(".reset");
var val1 = 0;
var val2 = 0;
var maxVal = 5;
var gameOver = false;
button1.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
if (val1 === maxVal) {
gameOver = true;
p1Display.textContent = val1;
button2.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
if (val2 === maxVal) {
gameOver = true;
p2Display.textContent = val2;
reset.addEventListener('click', function () {
'use strict';
var val1 = 0;
var val2 = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
gameOver = false;

color: green;

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Score Keeper</title>
<link rel="stylesheet" href="style.css">
<h1><span class="p1display">0</span> to <span class="p2display">0</span></h1>
<h3>Playing To : <span class="maxval">5</span></h3>
<input type="number" class="setVal" min="1">
<button class="button1">Player One</button>
<button class="button2">Player Two</button>
<button class="reset">Reset</button>
<script src="script.js"></script>

JS Fiddle Working Link


Don’t use var when resetting: in the resetting function, replace

var val1 = 0;
var val2 = 0;


val1 = 0;
val2 = 0;

val1 and val2 are already declared in an outside scope, redeclaring them in a narrower scope just creates different variables with the same name: the two variables val1 and val2 inside the resetting function are not the same as the ones outside the function. In fact they are never used, which is why JSLint reports a redeclaration and JSHint says they are unused variables.