Counting Button Clicks With JavaScript

Sometimes you need to know how many times the user clicks on an element. The most common solution is to create a counter as a global variable but with jQuery, you can prevent polluting the global scope by using data()to store the counter.

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com
    /ajax/libs/jquery/1/jquery.min.js"></script>
    <meta charset=utf-8/>
    <title>JS Bin</title>
</head>

<body>
<button>Click me</button>
</body>

</html>
<script>
    $('button')
        .data('counter', 0)
        .click(function () {
            var counter = $(this).data('counter');
            $(this).data('counter', counter + 1);
            alert($(this).data('counter'));
        });
</script>
Result:



No comments:

Post a Comment

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts