Track clicks on internal links with javascript while maintaining the ability to open then in a new tab
<p>I need to track the number of times certain links are clicked on my website.</p>

<p>I use a javascript based method that consists on binding the click DOM event to call my counting function and then redirecting the user to the page originally pointed in the href attribute of the link by using the document.location method.</p>

<p>This is an illustration of what my code is currently doing:</p>

<pre><code>&lt;!DOCTYPE html&gt;

&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Test file&lt;/title&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

    $(document).ready(function () {
        $(".myLink").on('click', function (event) {
            console.log(event.which);
            if (event.which == 2 ) { //it's a middleclick
                setTimeout(function () { 
                    alert("click counted!");
                }, 1000);
            } else { //it's a regular click
                setTimeout(function () { 
                    alert("click counted!");
                    document.location = "page_a.html";
                }, 1000);
                event.preventDefault(); //prevents the browser to load the linked page before the click is counted
            }
        });
    });

    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Test file&lt;/h1&gt;
    &lt;a class="myLink" href="page_a.html"&gt;Page A&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>This works with a regular click, but not in a few cases it doesn't do as expected:</p>

<ul>
<li>If the user right clicks on the link and then clicks on 'open in a new tab', the link is not counted.</li>
<li>If the user uses crtl+click (or command+click on a mac), which is the default shortcut for opening the link in a new tab, the click is counted but instead of opening in a new tab, it replaces the current tab like a regular click would do.</li>
</ul>

<p>If the uses uses the middleclick, which is also a common default shortcut for opening a link in a new tab, it does seem to work well.</p>

<p>My question is simple: how can I track my clicks while retaining the default behavior of being able to open links in a new tab in different ways.</p>

<p>Thanks!</p>
