0

I'm trying to open a new tab by detecting a control key during a click. I know the logic, but whenever I have it in place - the control key is not detected, and instead the browser inspector menu opens.

function handleClick(event) {
  event.preventDefault()
  if (event.ctrlKey) {
    return window.open('www.google.com', '_blank')
  }
  return window.open('www.google.com', '_self')
}

The element where the onClick is detected was a button. I've also tried with an anchor tag. Both have the same behavior. I've also tried:

function handleClick(event) {
  event.preventDefault()
  if (event.keyCode === 17) {
    return window.open('www.google.com', '_blank')
  }
  return window.open('www.google.com', '_self')
}

This will work but it's for the shift key:

function handleClick(event) {
  event.preventDefault()
  if (event.shiftKey) {
    return window.open('www.google.com', '_blank')
  }
  return window.open('www.google.com', '_self')
}
zero_cool
  • 3,960
  • 5
  • 39
  • 54
  • 1
    The event you are handling is a click event, therefore there is ho keyCode or ctrlKey or shiftKey – alanfcm Aug 07 '18 at 20:46
  • 1
    https://stackoverflow.com/questions/1828613/check-if-a-key-is-down – alanfcm Aug 07 '18 at 20:46
  • This is default functionality if every browser I have used, are you sure you need to implement this? – Adam H Aug 07 '18 at 20:47
  • @AdamH I asked the same question. I suggested shift or anything else really. – zero_cool Aug 07 '18 at 20:49
  • @alanfcm You are able to utilize the event API to listen for keyboard events during a click event: https://stackoverflow.com/questions/2445613/how-can-i-check-if-a-key-is-pressed-during-the-click-event-with-jquery – zero_cool Aug 07 '18 at 20:50
  • @zero_cool well, Shift will open the link in a new window, tab & middle click on a mouse will open in a new tab. Like I said this is default functionality so there is no need to code anything for this. – Adam H Aug 07 '18 at 21:45
  • Take a look at this, http://dmcritchie.mvps.org/firefox/keyboard.htm, specifically the section labeled 'Mouse Shortcuts (Keyboard+Mouse)' you can see there every browser supports Ctrl+Click to open in a background tab and Shift+Click to open in a new window. – Adam H Aug 07 '18 at 21:51
  • @AdamH The thing is - when I control-click the browser inspector menu opens - so even using what you've mentioned doesn't open a new tab. – zero_cool Aug 07 '18 at 22:40
  • @zero_cool Sounds like a config thing on your system. – Adam H Aug 08 '18 at 14:17

0 Answers0