When the user clicks, how can I collect the x / y as well as any link that could be clicked?

My feeling is that the button is not a link - misleading, but needs proof. So I want to record link clicks for analytic purposes, but also want unlinked clicks to be recorded as xy coordinates.

So, first I wanted to use $ ('a'), but that would only collect click links, so I want to do something like this:

$('html').click(function(event){
  var x = event.clientX; //will these change if the user has scrolled?
  var y = event.clientY;
  var link_clicked = 0;

  //this is what I'm not sure about:
  if($(this) <contains a link that was clicked>){
    link_clicked = $('<link clicked>').attr('title');
  }
  //so how do I find what link was clicked?

  var data = {x:x;y:y;link_clicked:link_clicked};
  $post(ajax_url, data, function(response){
    //do nothing
  });
});

      

So my first question is, in case a link is clicked, how do I find the link inside the html element that was clicked?

My second question is, does the X / Y client change when the user scrolls? For example, I want x = 420 to be the same if the user clicks on the same link at different scroll positions.

+3


source to share


1 answer


Try the following:

   var myItem=$('#myLink');
    $('html').click(function(event){
      var x = event.clientX; //will these change if the user has scrolled?
      var y = event.clientY;
      var link_clicked = 0;
      var clickedItem=event.target;
      if(clickedItem==myItem)
        console.log('clicked')
     ...
    });

      

EDIT:



var myItem=$('#myLink');
var x=myItem.offset().left;
var y=myItem.offset().top;
var clientX=event.clientX;
var clientY=event.clientY;

      

From this you can get the relative x / y values. If I understand you correctly.

Regarding your second question. ..
Yes, client X / clientY is resized by scrolling, because they are browser specific (compared to top browser, you may think) and not docs.

+3


source







All Articles