phpjquerywordpresswoocommercehitcounter

How to build Dynamic Visitor Counter


Hello guys I like to use fake dynamic visitor counter on my WooCommerce Store (WordPress) I like to add just below buy button so the counter like this: http://i.imgur.com/Fsq43OY.gif

In this example it sometimes decrease and sometimes increase completely dynamic.

I want the number to be run b/w 200-5000 so it wont increase beyond 5000 and neither decrease below 200 and not instant drop from 500-200 it should be slow and steady increase and decrease.


Solution

  • Using some JS you can pull that off. Use the Math.random() method and make the count change every n seconds with setInterval().

    function random(min,max)
    {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
    
    var initial = random(500, 2000);
    var count = initial;
    
    setInterval(function() {
      var variation = random(-5,5);
    
      count += variation
      console.log('You currently have ' + count + ' visitors')
    
    }, 2000)

    You can change the variation (here it's between -5 and 5) and also the interval (here it's every 2 seconds).

    Careful if you use JS, you can see the code in the source code... Have fun.


    EDIT

    Here's the code embedded in HTML, you can change interval (number of ms between two updates) and variation (how much the count can vary ±). You might want to change the interval to a higher value.

    Bonus: some styling with CSS

    #counter-area {
      padding: 2px;
      background-color: rgba(205, 204, 204, 0.19);
      border-radius: 2px;
      width: 300px;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
    
    #counter {
      color: white;
      background-color: red;
      padding: 4px 6px;
      border-radius: 5px;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    
    <body>
      <div id="counter-area">Real time <span id="counter"></span> visitors right now</div>
    </body>
    
    <script>
      function r(t,r){return Math.floor(Math.random()*(r-t+1)+t)}var interval=2e3,variation=5,c=r(500,2e3);$("#counter").text(c),setInterval(function(){var t=r(-variation,variation);c+=t,$("#counter").text(c)},interval);
    </script>
    
    </html>