Today I Learned

hashrocket A Hashrocket project

Cmd-click a link open in a new tab with JavaScript

We have a little jQuery plugin that makes entire table rows clickable by catching a click event on a table row and assigning window.location to the href of the anchor in that row – here’s a simplified example:

$('table').on 'click', 'tbody tr', (e) ->
  $a = $(e.target).closest('tr').find('a')
  location.href = $a.attr('href')

… but this doesn’t account for users who might want to hold down command and click on a row to open it in a new tab. In order to do that, we check the e.metaKey property that jQuery has so helpfully provided:

$('table').on 'click', 'tbody tr', (e) ->
  $a = $(e.target).closest('tr').find('a')
  href = $a.attr('href')
  if e.metaKey
    open(href, '_blank')
  else
    location.href = href

Voila! (Disclaimer: If you use something like this in the wild, make sure to do some other checks, like for multiple links in rows, the existence of checkboxes, that sort of thing – but this is the core to get you started.)

thanks to Pavel for correcting my initial implementation, in which I failed to realize metaKey is available on any jQuery event type)

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.