I'm trying to setup a text box that runs a function on keydown.
The code is:
var input = document.getElementById('Input_Number');
input.addEventListener('onkeypress', DrawDigits);
function DrawDigits(event) {
if (event && event.keyCode == '13') {}
}
Here's an example:
http://jsfiddle.net/wuK4G/
I know this is a common question, but I really can't find the answer. I've tried several methods and none of them work.
Try this:
function DrawDigits(event) {
if (event && event.keyCode == '13') {}
}
var input = document.getElementById('Input_Number');
input.addEventListener('keypress', DrawDigits);
// ^^
The eventlistener is keypress instead of onkeypress.
If you assign the eventlistener without addEventListener it is:
document.getElementById('Input_Number').onkeypress = DrawDigits
Maybe that was the confusion?
Related
I have a bunch of places where I have to code the same functionality for a click and an ENTER key press (keyup). I'm ending up writing event handlers like this:
$('#SomeElement').on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
// do what needs to be done
}
});
Is there an elegant way of handling this without the if statement? I hate the fact that it's an event handler specific to click and keyup, yet I have to check the event type inside the handler.
EDIT: I'm OK with abstracting out the if statement into a separate function. As long as I don't have to copy/paste the same line of code over and over again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(function( $ ) {
$.fn.clickOrKeyPress = function( callback ) {
this.on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback(e);
}
});
return this;
};
}( jQuery ));
You will need an if condition to confirm if the key pressed is enter. So you cannot completely get rid of if condition there.
But you can get rid of redundant conditions, like you don't need to check if the event type is keyup as we know if the event is not click, it will definitely be a keyup event.
So you can reduce your condition to
e.type === 'click' || e.keyCode === 13
My final solution - jQuery Event Extensions.
Create jQuery event extension specific for ENTER key.
$.event.special.enterkey = {
delegateType: 'keyup',
bindType: 'keyup',
handle: function (event) {
if (event.keyCode === 13)
return event.handleObj.handler.apply(this, arguments);
}
};
Now all I have to do is the following. Neat and elegant.
$('#SomeElement').on('click enterkey', function (e) {
// do what needs to be done
});
P.S. To all the incognito downvoters - you should be ashamed of yourselves.
I have not tested this yet, but maybe you can do named function and pass it with another callback to the event handler?...
Example (not tested!):
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
return callback;
}
}
$('#SomeElement').on('click keyup', clickKeyUpCallback(e, function() {
// your normal code here
}));
// EDIT
I realized the named function has to sit on a different place here if you want to do it this way and abstract the "if" part.
another example:
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback();
}
}
$('#SomeElement').on('click keyup', function(e) {
clickKeyupCallback(e, function() {
// do what ever needs to be done
});
});
I didn't understand clearly what you mean by "I have a bunch of places where I have to code the same functionality". But according to my understanding you want to attach some handlers to some elements that involve this check.
function doSomething(e) {
//do what needs to be done
}
function handleEvent(attachedHandler) {
return function(e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
attachedHandler(e);
}
};
}
$('#SomeElement').on('click keyup', handleEvent(doSomething));
lemme know if it helps you...
Is there any way how to submit form when you press some predefined key on your keyboard (for example ; key)? I was thinking about something with onkeypress, but dont know how to set it just for one specific key.
Yes, and you were right with thinking onkeypress, just pass in the event, and check which key is pressed with event.which:
function keyPressed(event) {
if (event.which == 186) //keycode for semi-colon
console.log("Semi-colon pressed!");
}
}
Now just attach this function to a keypress handler.
Edit: Got the keycodes from here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
You'll want to get the keycode and submit the form if it's the right keycode.
To get the keycode from an event, do:
$(document).on("keypress", function(event) {
var keyCode = event.keyCode;
var keyWhich = event.which;
if(keyCode = 'yourkey' || keyWhich = 'yourkey') {
$(form).submit();
}
});
For a full list of keycodes to replace 'yourkey' with, I'd recommend something like this cheat sheet. Just type your key in the input and use whatever value it provides as your function's logic
You can do this in jQuery:
$(document).ready( function() {
$(document).keydown(function(e){
if (e.keyCode == 186) { // ; key
$('#theform').submit();
}
});
});
See fiddle.
okay so I have the hotkey working just can't make it stop
$(document).keypress(function(e){
if(e.which == 13){
//Enter key is press do what you want
}
else if(e.which == 67 || e.which == 99){
//C key is press do what you want
window.location.href = "/html/credits.php";
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform").keypress(function(e){
e.stopPropagation(); });
Here is what I have to make it stop, the class of my input form is "registerform bgcolor2" but it wont work with either "input.registerform" neither with "input.registerform bgcolor2" I tried adding an ID to it with registerform as ID didn't work either :/
Is it being caused my AJAX? or am I missing something here?
(Sorry I reposted this just made a new account and cant find my old question back >.<)
I understand, that since you attach your event listener to the document object, all input accepting elements, such as textfields, selects, etc. will handle hotkeys, hence lose their normal behavior.
Take a look at line 44 in the jquery.hotkeys plugin. It excludes all input-accepting elements on initialization.
P.S. Maybe this plugin is useful as a whole for your task.
The key is to check, whether an event comes from a text-accepting input.
# only bind event to text-accepting elements, if they have been
# explicitly selected
# if your event variable happens to be called e, please adjust accordingly
if ( this !== event.target &&
( /textarea|select/i.test( event.target.nodeName ) ||
event.target.type === "text") ) {
return;
}
As your code stands now, you would need to insert this snippet at the beginning of the anonymous function, you bind to the keypress event.
Seems to be working just fine :)
example:
First example: http://jsfiddle.net/HenryGarle/SG5Um/
Second example: http://jsfiddle.net/HenryGarle/SG5Um/1/
New code:
$(document).keypress(function(e){
if(e.which == 13){
alert("Enter");
}
else if(e.which == 67 || e.which == 99){
alert("c");
//window.location = 'whateveryouwant';
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform.bgcolor2").live('keypress', function(e){
alert("Stopped");
e.stopPropagation();
});
Stops:
<input class="registerform bgcolor2" type="text">
<br>
Does not stop:
<input class="registerform" type="text">
Using this anything with ONLY registerform will act as normal but if it ALSO has bgcolor2 it will stop the event.
I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
I use jQuery to do something like this:
$('#searchbox input').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
EDIT: Since you're not binding to text box use:
$(window).on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
http://docs.jquery.com/Main_Page
You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.
Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.
This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html
function getFieldName(e) {
e = e || window.event;
var key = e.keyCode || e.which,
target = e.target || e.srcElement;
alert(target.name);
return (key != 13);
}
I have the above function called on body tag onkeypress = getFieldName(event);
I get the name of desired field but not able to check in IE as well as FF
if(target.name == 'check') {
// works fine in FF but in IE I'm not able
// to come inside this if-block, please suggest
}
thanks
I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.
To attach a function as an event handler, you can follow this simple example:
$(document).keypress(getFieldName);
jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:
$(document).keypress(getFieldName);
function getFieldName(e) {
alert(e.target.name);
if(e.which == 13) {
alert("Key pressed was enter");
} else {
alert("Key pressed was not enter");
}
}
You can view a quick demo here