How to Simulate Command+Click in JavaScript

For some reason you are simulating links with JavaScript like:

<!-- index.html -->
<div class="linkable" rel="/awesome">
  ...
</div>
// script.js
$('.linkable').on('click', function(event){
  const url = event.delegateTarget.getAttribute('rel')
  window.location.href = url
})

But you want to open the link in another tab as you do when clicking on the link with ⌘ Command pressed.

There you go:

// script.js
$('.linkable').on('click', function(event){
  const url = event.delegateTarget.getAttribute('rel')

  if (event.metaKey) {
    window.open(url)
  } else {
    window.location.href = url
  }
})

metaKey is Command key on macOS and Windows key on Windows.

You might want to check its support across browsers.

Bonus

There is also another property ctrlKey with the same behaviour but for Ctrl key on Windows and Control on macOS.

Written on February 5, 2021

Share: