Javascript Event How to - Count click and output click count








Question

We would like to know how to count click and output click count.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- ww  w . j a  v a  2  s . c  om-->
(function() {
    var oCount = document.getElementById('count');
    var oResult = document.getElementById('result');
    var nCount = 0;
    oCount.addEventListener('click', function(e) {
        e.preventDefault();
        nCount += 1;
        switch(nCount) {
            case 1:
                oResult.innerHTML = 'One';
                break;
            case 2:
                oResult.innerHTML = 'Two';
                break;
            default:
                oResult.innerHTML = 'More than 2';
        }
    }, false);
})();
}
</script>
</head>
<body>
  <a href="#" id="count">Count!</a>
  <span id="result"></span>
</body>
</html>

The code above is rendered as follows: