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)

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>
<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:



11 comments:

  1. Great blog! I would like to thank the efforts you have made in writing this post. I hope the same best work from you in the future
    duck life 3
    fnaf 4
    vex 3

    ReplyDelete
  2. This is really great work. Thank you for sharing such good and useful information here in the blog.

    Connect with our Roadrunner Customer Support Services group whenever you want, on the off chance that you need to get answers for any of the Roadrunner Password Reset issues.

    ReplyDelete
  3. Thanks For Sharing This, Very Interesting And Helpful Support Provide By this blog. Digital Signature Certificate in Delhi

    ReplyDelete
  4. Thanks for the post I actually learned something from it. Very good content on this site Always looking forward to new post. Digital Signature Certificate

    ReplyDelete
  5. Hello there, I found your site via Google while searching for a related topic, your website came up, it looks great. I have bookmarked it in my google bookmarks. content marketing strategy

    ReplyDelete
  6. I highly admire your post. Thanks for sharing such wonderful information, I see your post very often and share them on all social media channels.
    Private detective agency in Mumbai

    ReplyDelete
  7. Very good content on this site Always looking forward to new post. Apply Class 3 Digital Signature Certificate

    ReplyDelete
  8. I really enjoyed reading your blog, you have lots of great content. Please visit here:
    Digital Signature Certificate in Delhi

    ReplyDelete
  9. Love it! Very interesting topics, I hope the incoming comments and suggestion are equally positive. Thank you for sharing this information that is actually helpful.
    Class 2 Digital Signature Certificates

    ReplyDelete

More Posts

FOLLOW