Reputation: 21
Im trying to figure out a way to track how many times users have clicked a button on my website, so simply adding a value of 1 to the total number everytime it is clicked.
Im just not sure how I would store and access this number. New to html and javascript so please keep it simple, Thank you!
Upvotes: 1
Views: 5069
Reputation: 453
If your HTML is:
<div id="showCount"></div>
<input type="button" id="btnClick" value="Click me" onclick="CountFun();/>
Now the function to count is:
var cnt=0;
function CountFun(){
cnt=parseInt(cnt)+parseInt(1);
var divData=document.getElementById("showCount");
divData.innerHTML="Number of Clicks: ("+cnt +")";
}
Upvotes: 0
Reputation: 15509
Use a HTML5 data attribute to store the count as an attribute of the button rather than just a global variable and increment the count / update the data-count on each click.
Another client side solution would be to use local / session storage to store the count.
Note that if you want a server side solution and have access to it - you will need to use php or similar and save the data into a database.
$(document).ready(function(){
$('#clicker').click(function(){
var count = parseInt($(this).attr('data-count')) + 1;
$('#clickedNum').text('The button was clicked ' + count + ' times');
$('#clicker').attr('data-count', count);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button name="button" id="clicker" data-count='0'>Click Me</button>
<p id="clickedNum"></p>
Upvotes: 2
Reputation: 504
You can listen the click of corresponding button and store it.
<button name="button" >Click Me</button>
var ele = document.getElementsByTagName('button');
var numOfClick = 0;
ele[0].addEventListener('click', function() {
numOfClick = numOfClick + 1;
});
Upvotes: 0
Reputation: 567
<script type="text/javascript">
jQuery(document).ready(function($){
$(this).click(function(){
/** Perform Operations Here To Save Click Count **/
});
});
</script>
Upvotes: 2