Reputation: 5461
I try to implement the following code:
<a href = "http://www.google.com"/ id="external">go to google</a>
<span id="num1"></span>// to show the number of clicks so far.
<a href = "index.php" id="internal">go to home</a>
<span id="num2"></span>>// to show the number of clicks so far.
<script>
$(document).ready(function() {
var count1=0;
var count2=0;
$("#external").click(function(){
count1++;
});
$("#num1").html(count1);
$("#internal").click(function(){
count2++
});
$("#num2").html(count2);
});
</script>
I am not sure what I did above is right for the purpose of keeping track of the number of clicks on each link, and the problem is that when the page is loaded again, the count variable will be reset to 0, I wonder if I need to insert the count variable into database or is there even more efficient way to do this, any one could help me with that, any help will be greatly appreciated!
Upvotes: 1
Views: 770
Reputation: 75993
You can hi-jack the click
event for the links, stopping the normal flow, sending an AJAX request to your sever to log the click, and then redirect the user to the requested URL:
$('#external, #internal').on('click', function (event) {
var url = $(this).attr('href');
event.preventDefault();
$.get('path/to/server-side.php', { 'vote' : url }, function (serverResponse) {
window.location = url;
});
});
Note that .on()
is new in jQuery 1.7 and in this case is the same as using .bind()
.
You can also select all links:
$('a')...
Or you can add a class to links you want to log
$('.log-this-link')...
Upvotes: 1
Reputation: 8941
Javascript will be "reset" every time a page is loaded. In order to keep track of the clicks you'll have to store the data in a database.
Upvotes: 1