Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - override preventDefault() when click + ctrl pressed

Tags:

jquery

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/

like image 788
user007 Avatar asked Jul 25 '13 11:07

user007


1 Answers

$('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

like image 143
andreister Avatar answered Sep 19 '22 22:09

andreister