Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging hyperlink clicks on my website

I have a website, where I allow other developers to host content. My aim is to log clicks on every hyperlink (even the content that is hosted by other developers) ,which exists on the page.

My initial approach was as follows:

$('a').click(function(event)
             {
                //do my logging
                return true;
             }
);

Now with the above approach , I am facing the following issues:

  • Developers may have images inside the anchor link, so the events target is an image rather than href
  • Many developers have their own way of handling an href click , using an onclick event rather than a simply href='' attr
  • Some developers add their custom attr , to the tag, and have custom functions to handle the clicks

so basically , the issue is , there is a huge variety of anchor tags available, and logging clicks is not as simple.
Many cases allowed me to log the data I wanted, but a few cases , broke the code badly.

My aim to post on this forum was:

  • to discuss what is the right approach to do hyperlink clicks logging in a dynamic environment
  • is there a plugin out there , which allows a functionality like this.

I know facebook and google have this , but they have a totol control, on what is being hosted in their environments.

Any help is greatly appreciated.

like image 326
Neeraj Avatar asked Jan 11 '11 14:01

Neeraj


1 Answers

Adding a click handler to every link is not a good idea. You should make use of event delegation (which will only attach one event handler at the root of the document):

$(document).delegate('a', 'click', function(event) {
    // logging
});

Update (17.12.2011):

Since jQuery 1.7, one would use .on() [docs]:

$(document).on('click', 'a', function(event) {
    // logging
});

Regarding your problems:

Developers may have images inside the anchor link, so the events target is an image rather than href

Events bubble up as long as propagation is not canceled. It depends on what you want to log. With delegate the event.target property will point to the image, but this (inside the handler) will point to the a element.
So you should have no problems here (example: http://jsfiddle.net/cR4DE/).

But that also means to you will miss clicks if the developers cancel the propagation.

(Side note: You could solve this letting the event handler fire in the capturing phase, but IE does not support this (hence jQuery does not either).)

Many developers have their own way of handling an href click , using an onclick event rather than a simply href='' attr

This will not touch existing event handlers.

Some developers add their custom attr , to the tag, and have custom functions to handle the clicks

Not sure what you mean here.


It also depends on how the other content is included. E.g. the above code won't track clicks in iframes.

like image 182
Felix Kling Avatar answered Sep 16 '22 15:09

Felix Kling