Recreating a natural click event after a default prevention

$(document).on('click','a',function(e){ e.preventDefault(); var href = $(this).attr('href'); sendAnalytics("clicked a link",function(){ // on success callback, continue with link redirect window.location = href; // or location.assign(href); }); setTimeout(function(){ window.location = href; },5e3); // just incase callback never fires }); 

How can I simulate the default link behavior in this example? I notice that if I open a new tab ( control + click or middle-click ), it still redirects the current tab.

I know that I can catch every click and determine if it is a middle or left mouse, but is there an easier way to accomplish this, including things like control + click ?


So far, the only alternative that I see is to store the values ​​in a cookie, then read cookies on each pageload, send analytics and delete cookies.
+4
source share
1 answer

As far as I understand, you are trying to intercept the link click event, send some analytics data, and then recreate the click to continue navigation. So for this:

 function NewTab(url) { var newTab = window.open(url,"_blank"); newTab.focus(); } $("a").on("click", function(e) { // more efficient var href = $(this).attr("href"); if(e.ctrlKey) { // ctrl to open in a new tab sendAnalytics("clicked a link", function() { NewTab(href); }); setTimeout(function() { location.href = href; }, 5e3); } else { sendAnalytcis("clicked a link", function() { location.href = href; }); setTimeout(function() { location.href = href; } } }); 

First I create a new tab function that I can use if the user clicked the link to the link. Then I intercept the click, and if the Control key was pressed, I send the analytics and open the link in a new tab. Otherwise, I submit the analytics and then redirect the current tab. Backups still exist if the callback fails.

As a footnote, the easiest way to recreate the natural click of a link is $(this).click();

Hope this helps!
-v.p

0
source

Source: https://habr.com/ru/post/1496926/


All Articles