Reputation: 1391
I have a page where i want to count the number of clicks on a button. and the numbers are shown just below that button.
I tried to search and found this. I think this will not count the total number of clicks: Keeping track of number of button clicks
I am familiar with javascript code, so any help would be useful.
Upvotes: 1
Views: 46514
Reputation: 1
HTML:
<button id='click-me'>Click me please!!</button>
<div id='showCount'></div>
JS Code:
<script>
let count = 0;
let btn = document.querySelector('#click-me');
let divSection = document.getElementById('showCount');
btn.addEventListener('click', (e)=>{
count++;
divSection.innerHTML=`Number of Clicks are: ${count}`;
});
</script>
Upvotes: 0
Reputation: 462
You can do it this way:
<script>
var cnt=0;
function CountFun(){
cnt++
var divData=document.getElementById("showCount");
divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited
}
</script>
Or you can add event listner
documet.getElementById('[id of the button]').addEventListener('click', function(){
cnt++
var divData=document.getElementById("showCount");
divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited
});
Upvotes: 0
Reputation: 5123
Suppose your html is:
<div id="showCount"></div>
<input type="button" id="btnClick" value="Click me" onclick="CountFun();/>
Now the function is:
<script>
var cnt=0;
function CountFun(){
cnt=parseInt(cnt)+parseInt(1);
var divData=document.getElementById("showCount");
divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited
}
</script>
Upvotes: 2
Reputation: 256
HTML Code :
<button onclick="myFunction()">Try it</button>
JS Code :
var inc=0;
function myFunction() {
inc=inc+1;
alert(inc);
}
Upvotes: 4