Monday, November 10, 2008

[Tip] JavaScript: How to do a Ctrl-Click

You may want to make a link (or some other element) work when you hold down the Ctrl key before clicking the link.

This is possible in modern browsers and is done as follows:

document.onmousedown = clickElement;
function clickElement(e) {

var ctrlPressed = 0;
var evt = (navigator.appName=="Netscape") ? e : event;
ctrlPressed = evt.ctrlKey;
if (ctrlPressed) {
// Place code to run when Ctrl-Click done
}
return true;
}

Take note the above code works on the whole page and I have tested this on all top browsers:
IE 7, Firefox 3, Chrome, Safari and Opera 9.

Hope it helps someone.

6 comments:

Dan Pettersson said...

Great, just what I needed! :-)

Unknown said...

Thanks :)

Mark said...

Excellent, thank you!

Javi said...

OK, but when I click over an anchor while pressing Ctrl key, a new tab is opened. How can I avoid this issue? Have you solved?

Javi said...
This comment has been removed by a blog administrator.
Wolfgang Wohlkinger said...

Hi Javi

The Ctrl-Click code is just an event and has nothing to do with where a new window is opened.

You can open a new window two different ways: (1) using the target attribute in your <a> element (although this is no longer part of the W3C standard but still supported in all browsers) or (2) you can use JavaScript's window.open(...) method. The JavaScript way opens a new window in all browsers that I know about. The first way does often open as a tab in many browsers.