What am I missing in order to translate my jQuery onClick events into keypress events where a user can use a keypad?
The specific example is for a calculator. Using jQuery and the on click/touch events work perfect. However, when I try to introduce keyCodes I am not getting the results I think I should.
Here is my example code;
$(document).keypress(function(event){
var display = "0";
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode === 13){
alert(keycode + " = ENTER");
calcDisplay(total(), true);
}
});
Most of this I picked up from other successful solutions to similar issues. So the way I understand it is; if someone presses "enter" on the keyboard, I'd get my alert and then process my answer.
The jQuery version of this that works for me looks like this;
$(".button").on("click touch", function(){
var button = $(this).data("value");
if(button === "="){
calcDisplay(total(), true);
}
superNewb to JS here so much love ahead of time if this is something super foolish on my end.
keypress is meant to be used when characters are being inserted as input. keydown is meant to be used to detect any key.
quirksmode has a nice little write-up about the differences.
Instead of $(document).keypress use $(document).keydown.
Additionally, jQuery normalizes event.which, so instead of:
var keycode = (event.keyCode ? event.keyCode : event.which);
you can use
var key = e.which;
Related
I have an input that I want to allow the user to save the text either by pressing enter or by clicking anywhere else on the screen. Getting the code to process when the user presses enter is no problem. But I want to process the same code by triggering the jquery keyup event when the user clicks away just as if they pressed Enter on the input box instead. The theory isn't giving me an issue, but the keycode is either not being passed correctly or interpreted correctly when clicking away. When I alert the interpreted keycode, I get a "1" which doesn't equate to any keypress. What am I doing wrong?
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
var i = $.Event('keyup');
i.which = 13;
$(".attributeEdit").trigger(i); //Have also tried triggering off #openInput, too with no success
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
do stuff;
}
else{
alert("keycode: " + keycode); //This results in a "1" every time user clicks away
}
});
I found a solution to the end objective using Hiren Raiyani's suggestion of a function call. It doesn't actually answer the original question, but since it solved my problem, I'm hoping this will be useful to others that search. I created a function to "do stuff" and that way, I can call that function both after the Enter key is pressed and after the mouse is clicked.
function doStuff(x,y){
do stuff
}
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
doStuff(x,y);
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
doStuff(x,y);
}
});
I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
#input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.
So... how can I detect the ctrl?
Try using if (e.ctrlKey).
MDN: event.ctrlKey
Using onkeydown rather than onkeypress may help.
From http://www.w3schools.com/jsref/event_onkeypress.asp
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC) in all browsers. To detect only whether the user has
pressed a key, use the onkeydown event instead, because it works for
all keys.
Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.
function detectspecialkeys(e){
var evtobj=window.event? event : e
if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys
This is basically Rick Hoving's answer, but it uses keydown like Danielle Cerisier suggests
function detectspecialkeys(e) {
var evtobj = window.event ? event : e
if (evtobj.ctrlKey)
console.log("You pressed ctrl")
}
document.onkeydown = detectspecialkeys
Please note that you may have to click inside the preview box to focus before pressing ctrl
This question has been asked plenty of times before, but no answers I have found seem to solve my problem.
From a classic asp page I call a Javascript function
on each of my pages. The point is to fire a search button when a user enters search text and presses enter, rather than clicking on the button, or choosing from the Ajax provided selections.
This works fine in IE and FF, as has been the case for every other question asked along these lines.
Here is the Javascript. Can anybody tell me please how to have it work for Chrome as well as IE and FF ?
Edited following answer form Alexander O'Mara below:
Altered function call in body tag on page to use onkeyup instead of onkeypress - onkeyup="KeyPress(event)"
Altered JS function (also after heeding comments re duplication from others - thanks) as follows:
function KeyPress(e)
{
var ev = e || window.event;
var key = ev.keyCode;
if(window.event) // IE
{
key = e.keyCode;
if (key == 13)
{
window.event.keyCode = 0;
$('#btnSearch').click();
}
}
else if (key == 13)
{
btnSearch.click();
ev.preventDefault();
}
}
It seems to work sometimes and not others, and rarely on chrome currently. Is there a guaranteed way to have it work all the time ?
The main page of my site if you want to try it yourself is www.dvdorchard.com.au, your cursor will be sitting in the search box on arrival - enter a word > 3 chars and press enter, if you stay on the page it didn't work, if you move to the productfound.asp page it worked.
Thanks again.
You are looking for the keyup event (documentation). The keypress event is not consistent across browsers. See this question for information on the differences.
Update:
Since you are using jQuery, you can also remove the onkeyup="KeyPress(event)" attribute for you body, and replace your KeyPress function with the following (replacing the contents with your event handling code).
$(window).keyup(function(e){
/*YOUR CODE HERE*/
});
if(e.keyCode)
{
key= e.keyCode;
}
else
{
key = e.charCode;
}
Fire your event with onkeyup
read more
this should work in chrome. I don't know about other browsers
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
// done doing something with key
key=0
};
};
I am programming a jQuery plugin which tracks specific events. I have provided 2 JSFiddle examples for the sanitised code to assist at the end of the question.
I am struggling to fathom why 2 particular events are not firing. The first function tracks when the user triggers the backspace or delete keys within an input or textarea field. The code for this:
// Keydown events
$this.keydown(function (e) {
var keyCode = e.keyCode || e.which;
// Tab key
if (e.keyCode === 9) {
alert('tab key');
} else if (e.keyCode === 8 || e.keyCode === 46) { // Backspace and Delete keys
if ($this.val() !== '') {
alert('Backspace or delete key');
}
}
});
I only wish to track the error-correction keys when a field is not empty. The tab key in the above example works as expected within the conditional statement. The backspace and delete keys do not work when inside the plugin and targeting the element in focus.
The second event not firing is tracking whether a user becomes idle. It is making use of jQuery idle timer plugin to manipulate the element in focus.
// Idle event
$this.focus(function() {
$this.idleTimer(3000).bind('idle.idleTimer', function() {
alert('Gone idle');
});
}).focusout(function() {
$this.idleTimer('destroy');
});
With both of these events I have refactored the code. They were outside of the plugin and targeted $('input, select, textarea') and worked as expected. I have brought them inside the plugin, and set them to $(this) to manipulate elements currently in focus. For most of the functions, this has worked without fault, but these 2 are proving problematic.
The first JSFiddle is with the 2 functions inside the plugin. tab works, whereas the correction keys do not. Strangely, in this example the idle function is firing (it does not in my dev environment). As this is working in the JSFiddle, I accept this may be difficult to resolve. Perhaps suggestions on handling an external plugin within my own to remedy this?
Fiddle 1
The second JSFiddle has taken the backspace and delete key functionality outside of the plugin and targets $('input, select, textarea') and now works.
Fiddle 2
For Fiddle1:
if ($this.val() !== '') {
alert('Backspace or delete key');
}
Look at what $this actually is.
I don't want my website's user to use backspace to go to the previous page,
but I still want to keep the use of backspace,
just like deleting wrong typing.
How can I do?
Thanks a lot.
As others have mentioned there are methods in which you can monitor for backspace key events and perform different actions.
I recommend against catching the backspace key for a couple of reasons:
1) It's simply irritating and irritated users are likely to not return to your page.
2) Backspace is not the only method of returning to the previous page. There are other key combinations that can accomplish the same thing, as well as the obvious "back button".
Don't do it - but if you must, use onbeforeunload() rather than trapping browser specific key strokes.
Solution: Place the following code toward the end of all your pages that contain forms:
<!-- Block the Backspace and Enter keys in forms, outside of input texts and textareas -->
<script type="text/javascript">
function blockBackspaceAndEnter(e) {
if (!e) { // IE reports window.event instead of the argument
e = window.event;
}
var keycode;
if (document.all) {
// IE
keycode = e.keyCode;
} else {
// Not IE
keycode = e.which;
}
// Enter is only allowed in textareas, and Backspace is only allowed in textarea and input text and password
if ((keycode == 8
&& e.srcElement.type != "text"
&& e.srcElement.type != "textarea"
&& e.srcElement.type != "password")
|| (keycode == 13 && e.srcElement.type != "textarea")) {
e.keyCode = 0;
if (document.all) {
// IE
event.returnValue = false;
} else {
// Non IE
Event.stop(e);
}
}
}
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onkeydown = blockBackspaceAndEnter;
}
</script>
I have the following comments about what other people answered here before:
Someone said:
"Please don't. Users like
backspace-to-go-back; going back is
one of the most vital browser features
and breaking it is intolerably rude."
My answer to him is:
Yes, usually people DO use the back-button to go back, BUT NOT on pages with FORMS. On the other hand it is really easy for people to accidentally click near or outside an input text or textarea, and then press the back button, so they will lose all their edits, as someone else also noticed:
"Users aren't in a textbox and hit the
backspace, completely losing all the
form information they've just entered.
Wouldn't normally be a problem, but
for us, we're filling out lots of text
on long state forms."
The same undesired behaviour can also be said about the Enter key to submit the form, which usually is only desirable (if ever) for small forms with a few fields, but not for forms with many fields and select boxes and input boxes and textareas, in which most of the time you DO NOT want that the form is submitted when you press Enter.
So this is why I suggest the code above, which applies to all <FORM> tags the function suggested by webster, but without the checks for ALT, which I don't think is useful, and without the checks for CTRL+N and CTRL+R and CTRL+F5, which we don't want to block, because when they are used they are NOT accidental.
Unfortunately, the code above does not work in Firefox when you have DIVs and TABLEs inside your FORM! That is because the keydown event seems to not be propagated to the containing form, and instead the default (UNDESIRED!) behaviour is applied for the Backspace and Enter keys.
I couldn't yet find a solution for this one...
You can use the "onbeforeunload" property on the body tag to prompt the user that he is leaving the page.
You can simply use the following code snippets to block the backspace when the cursor is in texarea, text and password controls.
function onKeyDown()
{
if((event.altKey) || ((event.keyCode == 8) &&
(event.srcElement.type != "text" &&
event.srcElement.type != "textarea" &&
event.srcElement.type != "password")) ||
((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) ) {
event.keyCode = 0;
event.returnValue = false;}
}
Call this function from body tag onkeydown event
Filme Noi Cinema has the right answer, but the example code is a bit dated. I just needed this solution so I thought I would post the code I used.
//I use the standard DOM method for accessing the body tag, because the
//non-standard HTML DOM shortcuts are not stable. The correct behavior is
//dynamically attached to the entire body using the onkeypress event, which
//is the most stable event to target cross browser.
document.getElementsByTagName("body")[0].onkeypress = function (event) {
var a = event || window.event, //get event cross browser
b = a.target || a.srcElement; //get source cross browser
//the only thing that matters is the backspace key
if (a.keyCode === 8) {
//if you are a textarea or input type text or password then fail
if (b.nodeName === "textarea" || (b.nodeName === "input" && (b.getAttribute("type") === "text" || b.getAttribute("type") === "password"))) {
return true;
} else {
//backspace is disabled for everything else
return false;
}
}
};
This code needs to be executed before the user starts engaging the page. There are numerous ways to do this:
You can put the above code into any function that is already attached to the onload event.
You can wrap the above code that is bound to the page's onload event.
You can put the above code into a self executing function.
Examples:
//self executing function
(function () {
the solution code here
}());
//wrapper to onload event
document.getElementsByTagName("body")[0].onload = function () {
the solution code here
};
I am adding this code to Pretty Diff if you want to see an example in action.
You should be able to attach a onKeydown/Up/Press listener to your window. In this function, look at the keycode that was pressed, and at the event target. If the keycode is backspace, and the target is NOT an input box or a textarea, prevent the event.
I finally found one that works on all browsers.
It's by Hazem Saleh
His website address is:
http://www.technicaladvices.com/2012/07/16/preventing-backspace-from-navigating-back-in-all-the-browsers/
/*Starts here:*/
document.onkeydown = function (event) {
if (!event) { /* This will happen in IE */
event = window.event;
}
var keyCode = event.keyCode;
if (keyCode == 8 &&
((event.target || event.srcElement).tagName != "TEXTAREA") &&
((event.target || event.srcElement).tagName != "INPUT")) {
if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
event.stopPropagation();
} else {
alert("prevented");
event.returnValue = false;
}
return false;
}
};
/*Ends Here*/