debrata
debrata

Reputation: 139

how to count number of clicks on link laravel

How to count how many clicks have made on the link tag:

this is my code:

@foreach($news as $key => $value)
<li>
  <a href="" id="news_link" class="news_link"> 
   <h3 class="title">{{$value->title}}</h3>
  </a>
</li>
@endforeach

can anyone suggest what is the correct way to do this.?

$(document).ready(function() {
            var count = 0;
            $('.news_link').click(function() {
                count++;
            });
            alert(count);
        });

counter is not getting incremented on alert

Upvotes: 0

Views: 3164

Answers (1)

ThomasV
ThomasV

Reputation: 336

The best way to track this for analytics is to use Google Tag Manager to keep track of internal and external links.

If it is just for a function you could make use of Javascript and store it in a cookie, or if you want to store it like forever; in a database.

if(document.cookie.indexOf("clicks=") >= 0) {
   var clicks = getCookie('clicks');
} else {
    var clicks = 0;
}

$('#news_link').click(function() {
  clicks++;

  document.cookie = "clicks="+clicks;
});

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Or use Ajax to store it in lets say your database:

$(function () {
        $('#news_link').on('click', function () {
            clicks++;
            $.ajax({
                url: 'Ajax/StatusUpdate.php',
                data: {
                    count: clicks,
                },
                dataType : 'json'
            });
        });
    });

Upvotes: 1

Related Questions