<\/script>')

Ctrl + click on links with click handlers

I have a link (anchor) to which href is attached to go to a specific URL: "www.bla.com".

<a href='http://www.bla.com' /> 

I also have a click handler attached to a link that performs some actions and then opens an html view in the same window. Everything works perfectly.

However, when the user uses "ctrl + click" to open the link in a new tab / window, the click handler seems to take precedence and opens the html view in the same window. But I want to keep the behavior of "ctrl + click" and allow the user to open the link in a new tab / window (like a regular link). How can i do this?

Thanks in advance!

+6
source share
4 answers
 function process(e){ var evt = e ? e:window.event; if(evt.ctrlKey) alert("ctrlClicked"); }​ 

evt.ctrlKey will return true, if the control key is pressed, you can write your conditions in the "if" block, I checked it only on chrome and ff.

+6
source

Perhaps something like this?

 function onclick(e){ var event = e ? e:window.event; this.target = event.ctrlKey?"_blank":"_self"; }​ 
+1
source
 <a target="_blank" href='http://www.bla.com' /> 

Add target = "_ blank" inside the anchor tag.

0
source

The linked click event object will have the ctrlKey property set to true if the control key (or equivalent) was pressed when the click occurred. Check the event object and pressing the control key, do not "HTML view".

 <a href="#" onclick="alert(event.ctrlKey);">Click me!</a> 

However, if the user activates the link in some other way, you may or may not receive the click event.

eg.

  • right button → "open in a new tab / window" - there is no click event (Firefox, IE)
  • Tab, to focus on the link, press enter - dispatches a click event (Firefox, IE).
0
source

All Articles