Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to detect if user it trying to open a link in a new tab?
    primarykey
    data
    text
    <p>I'm writing a website in which all content is stored in the JavaScript environment, so it should be possible to navigate between "pages" without additional HTTP requests.</p> <p>I want to preserve the user's intent with respect to how links are opened, though. If a Mac user apple+clicks a link, for example, it should be opened in a new tab. But if the user wants to open a link in the current window, I want to avoid making a new HTTP request, and just use DOM manipulation to show the new content.</p> <p>Here's what I tried (<a href="http://jsfiddle.net/eH2pL/">JSFiddle</a>):</p> <pre><code>&lt;a href="http://yahoo.com" id="mylink"&gt;Yahoo!&lt;/a&gt; </code></pre> <pre><code>document.getElementById("mylink").onclick = function() { alert("clicked"); return false; } </code></pre> <p>It behaves as desired for normal left clicks, and for context menu actions, but not for clicks with a modifier key. I could check whether certain modifier keys are held, but that seems fragile.</p> <p>Twitter's website has behavior similar to what I want - when you click a username, it's normally an AJAX request, but if you click with a meta key held, you get a new tab.</p> <p>I'd prefer a plain JavaScript solution without libraries, unless this requires a bunch of platform-specific logic.</p> <h2>Update</h2> <p>I took a look at GitHub's code, which also has the behavior I'm after, and it does check for certain keys being held. So I'm accepting Chris's answer , since it seems unlikely that there's a better alternative.</p> <pre><code>$(document).on("click", ".js-directory-link", function (t) { return 2 === t.which || t.metaKey || t.ctrlKey ? void 0 : ($(this).closest("tr").addClass("is-loading"), $(document.body).addClass("disables-context-loader")) } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload