Tom Smykowski
Tom Smykowski

Reputation: 26129

How to handle every link click on a page in JS or jQuery?

People create their own websites using WYSIWYG creator i give them. These websites have links inside of them. Also they can explore the HTML of the website and put there their own links.

I would like now to handle every link click occurring in website created with my creator and log it to my server. I know how to pass the data from JS or jQuery to PHP server. But what i need to know is how to handle the moment when person clicks a link, postpone the redirection for some moment, and in this time get the url and title of this link and send to my PHP server.

So how to handle every link click (or location change) on website that structure i don't know and get the link and title of the link clicked?

Upvotes: 1

Views: 3923

Answers (5)

Pulkit Goyal
Pulkit Goyal

Reputation: 5664

$('a').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    var title = $(this).attr('title');

    // Send your data to php
    if ($(this).attr('target') === '_blank') {
        window.location.href = href;  // redirect to href
    } else {
        window.open(href);
    }
});

Upvotes: 4

Shyju
Shyju

Reputation: 218902

Why you want to wait till logging is completed for the redirection. Let it be an asynchronous call so that user don't need to wait. If you want to have your server page in a different domain, to tackle the cross domain ajax issue, use jsonp datatype.

$('a').click(function() {

   $.ajax({
     url:"yourwebsite/loggingpage.php?data="+$(this).attr("href"),
     dataType: 'jsonp' // Notice! JSONP <-- P (lowercase)         

  });

});

and in loggingpage.php, you can read the request data and log it to your persistent storage or wherever you want.

Upvotes: 0

mbx-mbx
mbx-mbx

Reputation: 1775

You can use jQuery to do this. Use the on event and bind to the click event of a element. You can then do an event.preventDefault(); do your logic and then continue as normal by getting the href from the target.

Upvotes: 0

Igor
Igor

Reputation: 34011

To intercept every link, just place this function somewhere that every page has access to (header/footer/etc.):

$('a').click(function(event) {
    event.preventDefault();//To prevent following the link

    //Your logic. attr('href') and attr('title')
});

Upvotes: 1

lcapra
lcapra

Reputation: 1550

jQuery("a").click(function(){  
  var href = $(this).attr('href');
  $.post('/', {link: href}).then(function(){ document.location = href; });
  return false;
});

just a try

Upvotes: 2

Related Questions