I have started using Dojo's new on module to add my events. It works fine, but now I've run into a problem. When using keypress event I can't seem to get the character value (for example "2" or "b") from the pressed key. Previously I've used the behaviormodule, and the connect module, and then I have been able to get it by using e.keyChar or e.charOrCode, but now they´re undefined.
I have an event set up like this:
on(element, 'keypress', function(e)
{
console.log(e.keyCode); //works, but not what I need
console.log(e.charOrCode); //undefined
console.log(e.keyChar); //undefined
});
How do I get the character of a pressed key when using this module?
In this case, I think what you want is to use e.keyCode in conjunction with the JS-native String.fromCharCode() in order to get the desired character value.
on(element, 'keypress', function(e) {
var character = String.fromCharCode(e.keyCode);
if (character === 'a') { // do a stuff } else { // do something else }
}
Related
For example, I want to implement something like do action when you typed sequentially shift-s then s, in JavaScript. I'm inspired by Autohokey, hotkey configuration software/language for Windows, so I'm looking for a library or way to implement something that in JS.
So far I found a library called hotkeys, but I have no idea to implement a sequential keyboard hotkey and didn't find any issue or question about it also, so here I am. So, how can I implement that in JS using the library or other library? Thanks.
This can be done easy with keydown event listener, no library needed for this
sAgain = false
document.addEventListener('keydown', function(event) {
if (sAgain && event.key.toLowerCase() == 's')
alert("shift-s then s clicked")
else if (event.shiftKey && event.key.toLowerCase() == 's')
sAgain = true
else
sAgain = false //stop listen if other key is clicked after shift-s
});
<h1>Press shift s then s<h1>
I have a 'keydown' event on javascript for navigating table using arrow keys:
my code as follows:
document.onkeydown= function() { keyDown();};
The implementation code as follows:
function keyDown(e){
var evt=(e)?e:(window.event)?window.event:null;
var key = evt.keyCode || evt.which;
if(key==38 || key==40){
alert("working");
}
}
How can I make it works on all browsers? What I am doing wrong here?
You need to pass the event variable that the system passes in to your function or use the standardised addEventListener method:
// Passing the event
document.onkeydown = function(e) { keyDown(e); };
// Using event listeners
document.addEventListener('keydown', keyDown, false);
Then you should rely on the event passed - do not use window.event - if the event is not passed to your function you have bigger issues to worry about than finding the event.
function keyDown(e){
if(e.which == 38 || e.which == 40){
alert("working");
}
}
I would learn more about the addEventListener method as assigning functions to the documents own onEvent attributes is not advised. What if you want to change this later? What if you want to add some code some of the time? Event Listeners are great for that and they don't modify the default behaviour here. You can add and remove these on the fly, making it much more versatile. Have a read here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
My jQuery is starting to get unnecessarily long. Is there a way to easily combine these 2 functions. My first thought is to create a custom event out of the key down function. Any solutions or suggestions on what to read up on would be appreciated.
$('th:nth-child(3):first').click(function () {
$('#dtSelect').val(2).change();
});
$('th:nth-child(3):first').keydown(function(event){
if(event.keyCode==13){
$('#dtSelect').val(2).change();
}
});
Simply:
$('th:nth-child(3):first').on('change keydown', function(event) {
if(!event.keyCode || event.keyCode==13){
$('#dtSelect').val(2).change();
}
});
This will fire on both change and keydown events, and will only call change() if event.keyCode does not exist (change) or is equal to 13 (keydown).
function combined(event) {
if (typeof event === 'undefined' || event.keyCode==13)
$('#dtSelect').val(2).change();
}
$('th:nth-child(3):first').click(combined).keydown(combined);
although in this case I don't think it's worth combining them.
I am new to scripting and for a function(e) e is event object can anyone please update me for my few concerns
it will created when a event is triggered so when it will removed . so every event an object is created?
where these objects get stored?
That is just an event handler variable.
Doesn't matter if its e or event
It really doesn't matter whether you use e or event or anyother word for this.
function (e):
When you use this:
function (e) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/1/ (fiddle for function (e))
function (event):
This is just a name you're giving to the current event, you can change that to
function (event) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/2/ (fiddle for function (event))
function (something):
Or even to this:
function (something) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/3/ (fiddle for function (something))
Their usage
You use these, to get the methods for the current object; such as event.keyCode, to get the keyCode which is used in a function where keyboard is used.
Where they are present
They are included in JavaScript and you don't need any more dependendies for it to work and you don't need any more coding work for it.
What a function looks like
They aren't removed, once a function is executed, it has an event parameter or what you can call argument. as:
function (event) { // event is the argument
if(event.keyCode == 13) { // using its method of keycode
/* and comparing its value to 13
* 13 is for enter
* you get a bool value; either true of false and do the coding */
}
}
Simple answer
From the fiddles you will get to the result that e doesnot require to be e only. It can be anything that you want to be written in the code. Something is no method in JavaScript, but usage of it at the first argument made it an event handler, and it got the methods of event.
They are not stored in browser, they are a part of every browser! When you say a browser supports this feature it means it includes all the files that are required to run a code.
I would like to use the following code to restrict input (to alphanumeric) into a text field:
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
The above code works great on a standard input field, but when I type into a field generated by Chosen, the function is not applied. The chosen plugin does generate a div containing <input type="text"> but $('input') doesn't seem to touch it. I'm guessing this is due to the timing of when the above code is applied..
Instead of .bind(), consider using .on() which will work for elements that are created dynamically.
Jack's answer works. But the important thing to understand is that the keypress event bubbles, so you can catch it anywhere up the node hierarchy, at a node that is not generated dynamically.
http://jsfiddle.net/KWv7Z/6/
$(document).bind('keypress', function (event) {
// Will fire for all elements, we only care for inputs
// Also allow navigation keypresses
if (event.target.tagName.toUpperCase() != "INPUT" ||
$.inArray(event.which, [8,9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,46]) ) {
return;
}
var regex = new RegExp("^[a-zA-Z0-9]+$");
// jQuery already normalizes event.which
var key = String.fromCharCode(event.which);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
This is also more memory friendly since it doesn't install a separate handler per input on the page.