1

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.

4 Answers 4

4

HTML Code :

  <button onclick="myFunction()">Try it</button>

JS Code :

 var inc=0;
 function myFunction() {
    inc=inc+1;
    alert(inc);    
 }
Sign up to request clarification or add additional context in comments.

Comments

2

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>

3 Comments

Thanks for your answer. That is working. Can you help me a little more? I want to display the text as "Number of Downloads: (Number)" Can you please edit the code to display it as above?
I saw another thing when i reload the page, the numbers got vanished. I want the numbers to be there always. If someone open my website from a different location, the number of clicks should be there.
When you reload the page the count no. will reset with 0. You can not achieve this with javascript. You have to use some server side code or coockies
0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.