Get javascript keydown event only if not writing [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript event handler on body but not on input
I wrote a short script that listens the keydown event, but i'd like to ignore it if i'm writing in a text field.
I have no idea about how to do it without strange tricks, like checking if there is a focus on one of the inputs.
Here is my code right now.
document.addEventListener('keydown', function(event) {
if(event.keyCode == 71) {
showSelected();
}
else if(event.keyCode == 13) {
closeModal();
}
});

This is a little tricky if you're doing things with contenteditable (like letting users write text inside of any divs/spans/boxes they want to on the page).
If so, this will take a little thinking and reworking (it's not that hard - just more involved).
However, you can check the event.target (element the event's happening on) for its tagName property, against a list of types you want to exclude.
function keyEvent (evt) {
var key = evt.keyCode,
el = evt.target,
type = el.tagName.toLowerCase();
// tag names are upper-case... almost always...
// so convert one way or the other, to be sure
if (type === "input" || type === "textarea") { return; }
/* do whatever you were going to do */
}
Should also likely be noted that this solution (and your code thus-far) aren't ghetto-IE compatible.
For that, you'd need to work with attachEvent and the window.event and window.event.srcElement properties, because they don't support addEventListener and the e/event function-parameter.

just check for the event.target
{
if (event.target.tagName.toUpperCase() == 'INPUT') return false;
// Do your Coding
}

Related

What's the most efficient way to compare 2 elements in javascript?

Here's my code to make txtKeyword input to have focus when the user presses a key.
var txtKeyword = document.getElementById("txtKeyword");
...
document.addEventListener("keypress", function(event) {
if(event.srcElement == txtKeyword)
{
return;
}
txtKeyword.focus();
}
I need to compare the elements to know if the message sender is the element on which I want to focus fail.
event.srcElement == txtKeyword
event.srcElement.id == "txtKeyword"
event.srcElement === txtKeyword
These comparison which is faster?
Considering id is a string, if the element's id is long, this way would not a ideal way.
My guess is that the last one should be the fastest because it doesn't do any coercion.

keydown event - key pressed on different systems

I have a number input, which I want user to by unable to insert any non-digit characters. We have attempted this in a number of ways:
We started with removing all non-numeric characters on blur:
$(my_input).blur(function() {
$(this).val($(this).val().replace(/[^\d]/, '')
}
The problem with the code above is that number field's val function returns empty string if the input is invalid. We definitively want a number field as our website is to be used on mobiles.
The option which I would prefer is to use keydown event:
$(my_input).keydown(function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
});
The above works almost as a charm. The problems are:
numeric keyboard not included in a range - this can be however easily fixed and is not a subject of this question.
For unknown to me reasons js on iOS is using different key codes, hence this is not working on huge part of mobile phones, iPads etc.. This is a deal breaker.
So the question - is there any way to determine which key was actually pressed with an keydown event. I have seen number of similar questions, none of them however covered those iOS differences. I've noticed that event has a 'key' property, however I am not sure how reliable this property is.
EDIT: I fell on this post which might be a neat way to solve your problem:
JavaScript: Avoiding hardcoded keycodes
It would boil down to
var digitCodes = "0123456789".split('').map(function (x) { return x.charCodeAt(0); });
There might be a better way to do this but you could detect if the device is running iOS (c.f. Detect if device is iOS) and use the appropriate keycodes (c.f. http://notes.ericjiang.com/posts/333).
var digitCodes;
if (isiOS()) {
digitCodes = keycodes.ios;
}
else {
digitCodes = keycodes.default;
}
if (digitCodes.indexof(e.which) != -1) {
...
}
Something like that...
You can try it this way
sample text box
<input type="text" name="sample" id="sample" onkeyup="positiveNumericOnly(this);" />
JS Code
function positiveNumericOnly(ele)
{
tempVal = ele.value.replace(/[^\d]/g, "");
if(tempVal != ele.value)
ele.value = tempVal;
}

Do not allow '&*' pair Textarea in Java Script

While adding text in a textarea, I dont want to allow '*' after '&'.
I want to check on Asterisk keypress, whether previous symbol added is '&', if yes, user cannot add '*'.
Kindly help, how to proceed.
You might be better off having a general function that runs after every "keyup" event which cleans up the textarea by removing any asterisks (*) immediately after an ampersand (&). This way, even if the user pastes some content which contains the invalid sequence (&*) it will still be cleaned up. So something like this:
myTextArea.onkeyup = function() {
myTextArea.value = myTextArea.value.replace(/&\*/, '&');
return true;
};
var input = document.getElementById("input");
input.addEventListener("keydown", function(e) {
if(e.shiftKey && e.keyCode === 55 && input.value.substr(input.value.length - 1) === "*") {
e.preventDefault();
}
},false);
This will add an event to check the incoming character and the last in the current input. If the incoming is shift+55 (thats shift-7 or &) and the last character in the input is "*" preventDefault will bail out of the event and not input what was just typed. This example wont work in IE because its using addEventListener but the same approach will work with IE attachEvent or event jQuery events for full cross browser.
Because you can paste using contextual menu, Ctrl-V, Shift-Ins, etc...
myTextArea.onchange = function() {
myTextArea.value = myTextArea.value.replace(/&\*/, '&');
return true;
};
And of course, this does not replace a good server side validation

Capture key press without placing an input element on the page?

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)
For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.
Attaching a keydown event to document works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:
$(document).keypress(function(e){
var checkWebkitandIE=(e.which==26 ? 1 : 0);
var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);
if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});
Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064
Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:
$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
$("body").append("<p>ctrl+z detected!</p>");
});
For modern JS, use event.key!
document.addEventListener("keypress", function onPress(event) {
if (event.key === "z" && event.ctrlKey) {
// Do something awesome
}
});
NOTE: The old properties (.keyCode and .which) are Deprecated.
Mozilla Docs
Supported Browsers
Detect key press, including key combinations:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 90) {
// Ctrl + z pressed
}
});
Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.
Code & detects ctrl+z
document.onkeyup = function(e) {
if(e.ctrlKey && e.keyCode == 90) {
// ctrl+z pressed
}
}
Attach a listener to the keydown event instead of keypress, since the latter is now deprecated.
window.addEventListener('keydown', keyDownHandler);
The keydown event triggers continuously while the key is pressed. If you wanna have it fire only once, inside the handler use the event.repeat property as so:
keyDownHandler(event) {
if (!event.repeat) {
<code here will only be executed once while the key is pressed>
}
}
Remember to remove the listener when not needed anymore.
window.removeEventListener('keydown', keyDownHandler);

Is possible to capture KeyDown event when current document is in design mode?

As you know, most of rich text editor use iframe to create WYSIWYG editor. In iframe contain document that is in design mode. I want to capture key down event when user press '#' character in rich text editor for displaying autocomplete for it.
By the way, i cannot see any fired event inside design mode. How can I solve this question?
It's perfectly possible to capture all key events in documents with designMode turned on, though you have to use addEventListener on document in Firefox (and possibly others) rather than assigning your handler to document.onkeypress.
To capture the user typing the '#' character (or indeed any printable character), you should use the keypress event rather than keydown.
// Assuming you have a reference to your iframe in a variable called 'iframe':
function handleIframeKeyPress(evt) {
evt = evt || iframe.contentWindow.event;
var charCode = evt.keyCode || evt.which;
var charTyped = String.fromCharCode(charCode);
if (charTyped === "#") {
alert("# typed");
}
}
var doc = iframe.contentWindow.document;
if (doc.addEventListener) {
doc.addEventListener("keypress", handleIframeKeyPress, false);
} else if (doc.attachEvent) {
doc.attachEvent("onkeypress", handleIframeKeyPress);
} else {
doc.onkeypress = handleIframeKeyPress;
}

Categories

Resources