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.
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.
Here's what I tried (JSFiddle):
<a href="http://yahoo.com" id="mylink">Yahoo!</a>
document.getElementById("mylink").onclick = function() {
alert("clicked");
return false;
}
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.
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.
I'd prefer a plain JavaScript solution without libraries, unless this requires a bunch of platform-specific logic.
Update
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.
$(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"))
}