I cannot get preventDefault()
to work.
Here are some different code variations I have tried:
First:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
return false;
}
});
Second:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
evt.preventDefault();
}
});
Third:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
evt.preventDefault();
return false;
}
});
Only alert works.
Everything works on Opera,but not on Chrome and IE
Also tried keydown
and keypress
.
On keypress
script doesn't work.
$('#thetext').keydown(function(evt){});
neither works this.
Here is whole code: http://bbullett.tk/test/kakey.html
Key 192 = `
I'm trying to insert some text or symbol instead of `
see working example here http://jsfiddle.net/WGSvm/
In all three examples you have used
I would say use particular div id instead of
$(document).keyup(function (evt) { });
like
$("#DivIdName").keyup(function (evt) { });
and also useonkeypress
strictly, because if you useonkeyup
it has already executed its default task of printing or whatever it is.Listening to
keyup
event is too late for callingpreventDefault
, try listening tokeypress
orkeydown
instead.Note that jQuery normalizes
which
property and it's cross-browser.http://jsfiddle.net/763ys/
You are using JQuery, which normalises the differences between browsers, so you only need to to check the evt.which property. See the JQuery documentation: http://api.jquery.com/keyup/
As others have said - keyup is too late to stop the processing of the key. Use keydown or keypress instead. http://api.jquery.com/category/events/keyboard-events/
There is no default behaviour for
.keyup()
; it fires after the key press which triggers the default behaviour. Use.keydown() or
.keypress()` instead.source: http://api.jquery.com/category/events/keyboard-events/