Javascript to count the number of times user clicks on a button

In some scenarios we might need to count the number of times a particular user has clicked a button or any other element in a web page. There is no direct way like a static variable to count the number of times the user has clicked .

Below javascript code can be used to count the number of times a user has clicked an element .

function addCategory()
{
if ( typeof addCategory.no == ‘undefined’ )
addCategory.no =1;
else
addCategory.no =addCategory.no +1;

}

<input type=button onclick=”addCategory()”>

Explanation:

addCategory.no—–>contains total number of times the addCategory() get invoked.
no—-> is variable name. Here it acts as member variable for addCategroy() function.
addCategory—->is function name. Javascript treats every function as object. That’s why we are accessing variable as addCategory.no

Posted in Javascript Tagged with: , , ,