1

I have code below by which I get the Ctrl+w event of browser but it's only working in Firefox not in other browsers. I found that there is problem with keydown/keypress. Is there any way to write a code to browser compatibility for both event(keydown/keypress).

here is my code:

$(window).keydown(function (event) {
    event.preventDefault();
    if (event.which == 119 && event.ctrlKey) {
        alert("Ctrl-W pressed");
    }
    return false;
});

2 Answers 2

0

Use keypress instead of keydown: demo

$(window).keypress(function(event) {
        event.preventDefault();

        if (event.which == 119 && event.ctrlKey) {
            alert("Ctrl-W pressed");
        }    

    return false;
});
2
  • It's not working in chrome and IE. I want this code should work in all browsers. Feb 12, 2014 at 6:19
  • In chrome not possible, You can't override browser behaviour with js :) Feb 12, 2014 at 6:21
0

Here is solution for only keys that are not set default

Also you can not overide browser default behaviour using JS

Here is quick solution

Solution 1(Quick)

CODE

$(document).keypress("w",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});

Fiddle http://jsfiddle.net/J4t5d/1/

Solution 2

you can do this easily with js library which is shortcut.js

Solution 3

You can do trick like this :)

$(window).keydown(function(event) {event.preventDefault();
    if (event.which == 87 && ctrlMode == true) {
        alert("Ctrl-W pressed");
    }    
     return false;
});
$(document).keydown(function(e){e.preventDefault();
 if(e.ctrlKey){
        ctrlMode = true;
 }
});
$(document).keyup(function(e){e.preventDefault();
 if(e.ctrlKey){
     ctrlMode = false;
 }
});

Fiddle http://jsfiddle.net/J4t5d/5/

Hope it helps you :)

1
  • It's not working. I want this code should work in all browsers. Feb 12, 2014 at 6:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.