user007
user007

Reputation: 3243

jQuery - override preventDefault() when click + ctrl pressed

I am using preventDefault() for preventing default behavior of an an anchor button, but I want to make this button to do default behavior when clicked with keyboard ctrl button,

JS code

$('a').click(function(e){
    e.preventDefault();
});

HTML code

<a href="http://google.com">Go to the best search engine</a>

Here is the playground: http://jsfiddle.net/sKDuA/

Upvotes: 7

Views: 3360

Answers (2)

vhbazan
vhbazan

Reputation: 1427

If someone needs to fix this for both Mac and Windows this does the trick:

$('a').click(function(e) {
    if (!e.ctrlKey || !e.metaKey) {
        e.preventDefault();
    }
});

Upvotes: 1

andreister
andreister

Reputation: 13871

$('a').click(function(e) {
    if (!e.ctrlKey) {
        e.preventDefault();
    }
});

Other intertesting options:

  • e.altKey - to check if Alt was pressed
  • e.shiftKey - to check if Shift was pressed
  • e.button - to distinguish between right, left of middle mouse clicks
  • e.which - same as above, but also works for keyboard
  • full documentation here

One more note, as you asked about documentation so seem to be really interested ;)

It's possible to debug in jsfiddle - just put debugger in your js code and run as usual. Your browser (I use Chrome) would stop on the debugging line, and you could examine the e object in the watches:

enter image description here

Upvotes: 14

Related Questions