JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Using jQuery to Create a Click Counter

January 23, 2017 by Krishna Srinivasan Leave a Comment

Here’s a cool jQuery snippet that you can use to create a click counter. The way it works is that each time an element is clicked, the counter (which starts at 0) goes up by one. The counter can be applied to the clicking of any particular elements or multiple elements, and you can choose whether or not to display it somewhere on your page or site, or log the counter to the console, or use the counter in a function.

The code for creating a counter isn’t too complicated and shouldn’t be more than a handful of lines of code. While it doesn’t have to be a counter that is triggered by a click (it could be triggered by any number of events), in this particular example, it is a click counter. Feel free to customize the code so that its functionality appeals to you and so that it works with your HTML and with your desired elements.

$(element)
    .data('counter', 0) // begin counter at zero
    .click(function() {
        var counter = $(this).data('counter'); // get
        $(this).data('counter', counter + 1); // set
        // do something else...
    });

Filed Under: JavaScript, jQuery Tagged With: Click Counter, jQuery

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved