Click Counter not working - javascript

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;
};

Related

Why is addEventListener increment code not working?

I am still learning and I like to know why certain codes happen the way they do. So, created a code to increment by 1 when a button is clicked and have that displayed on the screen. However, when using addEventListener, it didnt work. It only added 1 and never increased by 1 again.
But when I used onclick Event in html, it worked fine and incremented. What could be the issue? Here are the codes:
HTML
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
Player One
JS code with addEventLister. This doesnt increment, But when I used consol.log(count), it increased by 1 but grayed out. Kindly check the attached screenshot
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', () => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
countNum()
})
This is the JS code that I used onclick and added the function to the button directly. This is working fine. I want to know what made the addEventListener not to work?
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
console.log(count)
}
The button with the html:
<button onclick="countNum()" class="playerOne">Player One</button>
You're resetting count to 0 every time the function is called.
You need to use the inner function as the event listener, not the outer function. You can do this with an IIFE that returns the inner function.
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', (() => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
return countNum;
})())
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
<button class="playerOne">Player One</button>
You should move your var count = 0 outside from addEventListener function. Otherwise on each click you will reset your counter and then immediately increment it, which means you always assign to innerHTML value equal to 1.
Fixed example with addEventListener:
var playerOne = document.querySelector('.playerOne');
var firstScore = document.querySelector('.firstScore');
var count = 0;
var countNum = function() {
count++;
firstScore.innerHTML = count;
};
playerOne.addEventListener('click', countNum);
Working example.

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>

Create multiple buttons in JavaScript

I have checked for syntax errors and it does seems like everything is okay, it just does not do anything when loading the body of the page. I know I have linked the script correctly to the html file, because I've already implemented a JS Clock which displays itself in the page as you can see in the pen. Is there anything wrong with my code? Why aren't my 10 buttons displaying? I fear Bootstrap may be preventing me from getting my buttons show up.
My purpose is to create 10 buttons, so that I don't have to write the same code 10 times.
The Codepen is just to check out my code, I work on Atom usually. This is my Codepen!
<div class="container-fluid" id="buttons">
</div>
function createButtons() {
for(i = 0; i < 11; i++) {
var button = document.createElement("<button type=\"button\" class=\"btn btn-outline-success\">Chapter[i]</button>");
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
}
document.body.addEventListener("load", createButtons(), false);
The function createElement accept a tag name as argument.
var Chapter = [0,1,2,3,4,5,6,7,8,9,10];
for(i = 0; i < 11; i++) {
var button = document.createElement("button");
button.innerHTML = Chapter[i];
button.className = "btn btn-outline-success";
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}

Why does this JS button only add the div once? if i click again nothing happens

What i want it to do is add an additional div every time the add button is clicked. what happens instead is it adds it once and then never runs through the code again. I have tried printing out the count and it increments once and never populates again. If i delete the code about inserting the div the count increments every time the button is clicked. What am i missing here?
var count = 0;
button.onclick = function()
{
popup.document.body.innerHTML += '<div id="queryPart-'+ count+'"></div>';
count = count + 1;
};
here is the whole code block
var popup = open("", "Popup", "width=600,height=200,top=600,left=200");
//var div = popup.document.createElement("DIV");
//div.id = "div";
popup.document.body.innerHTML += '<div id="queryPart-0"></div>';
var div = popup.document.getElementById("queryPart-0");
queryLine(div);
var button = popup.document.createElement("BUTTON");
var t = popup.document.createTextNode("ADD");
button.id = "addbutton";
button.onclick = function()
{
popup.document.body.innerHTML += '<div id="queryPart-'+ count+'"></div>';
count= count + 1;
};
button.appendChild(t);
div.appendChild(button);
You should use Node.appendChild() instead because DOM manipulation is a better approach. You only want to add to the existing document, without obstructing or disturbing other elements. By appending directly to the HTML of the body, you are disassociating the original button with the click handler.
Googling this issue returns many helpful resources:
https://www.google.com/#q=innerhtml+removes+listener
After a bit on redirecting, I found one of the first questions related to this issue, here on Stack Overflow:
Is it possible to append to innerHTML without destroying descendants' onclick functions?
Broken
var button = document.getElementById('addBtn');
var count = 0;
button.onclick = function() {
console.log('click');
document.body.innerHTML += '<div class="queryPart-'+ count+'">' + count + '</div>';
count++;
};
<input type="button" id="addBtn" value="Press Me" />
Corrected
var button = document.getElementById('addBtn');
var count = 0;
button.onclick = function() {
var queryDiv = document.createElement('DIV');
queryDiv.className = 'queryPart-' + count;
queryDiv.innerHTML = count;
document.body.appendChild(queryDiv);
count++;
};
<input type="button" id="addBtn" value="Press Me" />
You could also...
set the outerHTML of a div, so that you don't have to create the Element as you see in the above example.
var button = document.getElementById('addBtn');
var count = 0;
button.onclick = function() {
var queryDiv = document.createElement('DIV');
document.body.appendChild(queryDiv);
queryDiv.outerHTML = '<div class="queryPart-'+ count+'">' + count + '</div>';
count++;
};
<input type="button" id="addBtn" value="Press Me" />
This is happening because of the way innerHTML works.
(get) .innerHTML -> "Enumerate all of the elements in this DOM into "HTML" format, and return it as a string"
(set) .innerHTML = -> "Destroy all elements in this DOM, and then create new ones using the HTML that has been provided."
You're destroying your button, and its event listener, during the set operation. You'll likely want to create your button using a more manual method, like document.createElement, and then append it using myElement.appendChild. These operations are pretty common, so I don't think it would make sense to give a full tutorial here - this could also be easier with a framework like JQuery, which has many methods for adding new DOM elements.
Looks like you messed up the order of the
" and '
try:
var count = 0;
button.onclick = function()
{
popup.document.body.innerHTML += '<div id="queryPart-'+ count + '"></div>';
count = count + 1;
};

Displaying an average of two variables

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();
})

Categories