Jitender Chand
Jitender Chand

Reputation: 93

click count function not working?

i want to count every mouse click hits by user so i create a function but it is counting only first clicks. I create a variable to store count values.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>clicks</title>

<script type="text/javascript">



function clickcount (){

var clicks=0;   
    document.getElementById('count').value= ++clicks;


    }

document.onclick=clickcount;
</script>


</head>

<body>

<input type="text" id="count" />
</body>
</html>

Upvotes: 1

Views: 1248

Answers (3)

Kevin Ji
Kevin Ji

Reputation: 10489

To avoid polluting the global namespace, you could wrap your code in an anonymous function and store your clicks in a closure:

(function () { // Begin wrap with anonymous function
    var clicks = 0;
    function clickcount() {
        document.getElementById("count").value = ++clicks;
    }

    // Attach to onload
    window.onload = function () {
        document.onclick = clickcount;
    };
}()); // End wrap with anonymous function

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270617

That's because you declared var clicks inside the function. It gets overwritten with 0 each time it is called. Declare it outside the scope of the function.

var clicks = 0;
function clickcount (){
    document.getElementById('count').value= ++clicks;
}

The var keyword initializes a variable. JavaScript will make available vars defined at a broader scope inside narrower function scope. So calling var clicks = 0 outside the function places clicks at the global (window object) scope.

Upvotes: 2

user1106925
user1106925

Reputation:

You need to make clicks global so that the function continues to increment the same variable...

var clicks=0;
function clickcount (){

    document.getElementById('count').value= ++clicks;

}

Upvotes: 3

Related Questions