Subscribe For Free

Thursday, January 25, 2018

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>
    <script src="
    <meta charset=utf-8/>
    <title>JS Bin</title>

<button>Click me</button>

        .data('counter', 0)
        .click(function () {
            var counter = $(this).data('counter');
            $(this).data('counter', counter + 1);

No comments:

Post a Comment

click it