How to override *only* left click on anchor?

I know I can use event.preventDefault() to stop a link from being followed. But I only want to prevent the default action on a plain left-click or touch-tap. shift-left-click, ctrl-left-click, right click, and middle click should all perform the default action.

How can I detect a plain left-click or touch tap?


Solution 1:

You can check MouseEvent properties like button, altKey, shiftKey & ctrlKey to do this

document.getElementById('test').addEventListener('click', function(event) {
  snippet.log('button: ' + event.button);
  snippet.log('ctrlKey: ' + event.ctrlKey);
  snippet.log('shiftKey : ' + event.shiftKey);
  snippet.log('altKey : ' + event.altKey);

  if (event.button == 0 && !event.ctrlKey && !event.shiftKey && !event.altKey) {
    event.preventDefault();
  }
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<a id="test" href="http://stackoverflow.com/">test</a>