Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Oct 2009
    Posts
    478
    Thanks
    7
    Thanked 3 Times in 3 Posts

    add counter to onclick action

    I have a custom autoselect field, and when they click a suggestion, guess what the selected phrase is added to the field. But what I would really like is to be able to count how many times each phrase is clicked.

    How might I be able to do this ?

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,460
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Code:
    <button id="clicker1" class=tracked >example</button>
    
    <script>
    
    [].slice.call(document.querySelectorAll("[id].tracked")).map(function(elm){
      var tot=localStorage["cnt"+elm.id];
      if(tot){ elm.title="Clicked "+tot+" Times"; }
      elm.onclick=function(){ 
           localStorage["cnt"+elm.id] = Number(localStorage["cnt"+elm.id] || 0) + 1; 
           elm.title="Clicked "+tot+" Times";
      };
    });
    
    </script>
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #3
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    @rnd me: your onclick seems to work better with
    Code:
    elm.title="Clicked "+localStorage["cnt"+elm.id]+" Times";
    as the last line, but I guess it depends on the effect you are going for

    @needsomehelp: if you want the counter to reset on every page load you can do something like this:
    Code:
    <button title="clicked 0 times" id="clicker1">example</button>
    <script>
    document.getElementById("clicker1").onclick=function(){
    var thenum = this.title.replace( /\D+/g, '');
    this.title='clicked '+(++thenum)+' times';
    }
    </script>


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •