Issue
I’m trying to create an easier counter. At first, only adding a number worked for me, but reset did not work, so then I decided to look at the tutorial on YouTube and combined my code with it, but errors came out.
codepen – https://codepen.io/Agasfer/pen/vYayEwv
<!DOCTYPE html>
<html>
<head>
<title>CoderslangJS click counter</title>
</head>
<body>
<h3>CLICKS:</h3>
<p id="clicks">0</p>
<button type="button" id="incrementCounterButton" onClick="clickHandler(plus)">Click me</button>
<button type="button" id="resetCounterButton" onClick="clickHandler(reset)">Reset</button>
<script>
let button = document.getElementById('incrementCounterButton');
button.onClick = clickHandler;
let par = document.getElementById('clicks');
let count = 0;
let res = document.getElementById('resetCounterButton');
function clickHandler(button){
if(button == plus){
++count;
par.innerHTML = count;
};
if(button == reset){
count = 0;
};
};
I decided to look at the tutorial on YouTube and combined my code with it, but errors come out.
Solution
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<main>
<h1>My other page</h1>
<h3>CLICKS:</h3>
<p id="clicks">0</p>
<button
type="button"
id="incrementCounterButton"
onClick="clickHandler('plus')"
>
Click me
</button>
<button
type="button"
id="resetCounterButton"
onClick="clickHandler('reset')"
>
Reset
</button>
</main>
<script>
let button = document.getElementById('incrementCounterButton');
button.onClick = clickHandler;
let par = document.getElementById('clicks');
let count = 0;
let res = document.getElementById('resetCounterButton');
function clickHandler(button) {
if (button == 'plus') {
++count;
par.innerHTML = count;
}
if (button == 'reset') {
count = 0;
par.innerHTML = count;
}
}
</script>
</body>
</html>
"clickHandler(plus)" – here plus is a parameter that should be defined a type. If it is string then needs to put inside double or single quote like ‘plus’.
clickHandler(button) {
if (button == 'plus') { }
}
Here button parameter receiving value as a string so that should be match with string.
Answered By – Parkar
Answer Checked By – Jay B. (BugsFixing Admin)