I'm building a virtual keyboard that assigns images to keycodes, and appends them in spans after a keydown event. Problem comes with the DELETE functionality.
if (e.keyCode == 8) {
$('span:last').remove();
}
Since everything happens outside of a textarea or input field, this triggers the browser's back button. Any help would be much appreciated!
That's a backspace, not a delete, for starters.
Next, backspace is the keyboard shortcut for "Back", so you MUST return false; in the event handler to prevent that default action taking place.
return false in whatever function you're handling that event. That should stop the default behavior.
Related
In chrome and firefox (and maybe others), if you've got an input focused, pressing "space" and "enter" clicks them for you. I'm making an HTML 5 game and I want to rewrite how space and enter reacts on focus and the default behavior is getting in my way. Is there a way to turn this default behavior off in most browsers?
Here's a jsfiddle demonstrating the problem.
<button>Button<button>
$("button").on("click", function(event) { alert("Clicked"); });
If you click on the button, it displays the alert which is good. But if you press "space" or "enter" after you click it, it also alerts. I want to prevent this behavior so that I can write my own without them interfering.
You can fix this by using event.detail. That will return the amount of times the button has been clicked. If you press enter, this returns 0, since you clicked it 0 times, and if you click it via your mouse, it returns the amount of times you clicked the button.
To access event.detail, you need to access the original event object. This can be done via event.originalEvent in the jQuery event object. So, if you just put an if statement in your script:
if (event.originalEvent.detail != 0) {
//your click event code
}
then it'll only run if you actually click the button via your mouse.
This will be much more accurate than checking if the button has :focus, since the button automatically gets focused when you click it, so doing that would disable the button after a single click.
Check if a button is active:
$("button").on("click", function(event) { alert("Clicked"); });
$(document).on('keydown', function(e){
if($(document.activeElement).is('button') &&
(e.keyCode === 13 || e.keyCode === 32))
e.preventDefault();
});
You could also use jQuery's :focus selector, which should return the same element, $(':focus').is('button').
http://jsfiddle.net/zmH5V/4/
other option, is to blur the object right after clicking it:
<button id="mybutton" onclick="myFunction();this.blur();">button</button>
I find that solution easier to use, because it requires less code-lines, and gets the same results:
while the button is blured, it has no contact with the keyboards events, and that solves the problem.
I'm writing code in JavaScript, targeting Chrome.
Now, consider what happens when:
I press Space/Backspace on a webpage vs
I press Space/Backspace on a textbox
BY using (goog.events.listen js/document.body ...) I can listen for Space/Baskspace events and react on them. However, the browse still processes them i.e. when I press Space the browser still scrolls down and when I press Basckspace, the browser goes to the previous webpage.
I would like to prevent this "default behavior" -- i.e. I want to process the Space/Backspace events, and I want the browser to ignore them.
Thanks!
Return false from the event handler to cancel the event.
document.body.onkeydown = function killSpace(e) {
if (e.keyCode === 32) {
return false;
}
};
Please don't kill keyboard shortcuts globally like this. It hurts usability. Only prevent default behaviour when some custom widget on the page has focus, and this element can lose focus using a keyboard shortcut like tab.
On a JavaScript page, I pop up an alert if the user hits the enter key by using
if(evt.keyCode == 13){
alert("Return Key Pressed");
}
but the event does not fire when I hit the return key on the iPad. How do I catch the event?
The iPad keyboard does fire the keypress event with a key code of 13 if you press return. This sounds like you've got something else going awry
Here's a quick jsfiddle to verify with: http://jsfiddle.net/359wG/
According to https://api.jquery.com/keypress/
The keypress event is sent to an element when the browser registers
keyboard input. This is similar to the keydown event, except that
modifier and non-printing keys such as Shift, Esc, and delete trigger
keydown events but not keypress events. Other differences between the
two events may arise depending on platform and browser.
A keypress event handler can be attached to any element, but the event
is only sent to the element that has the focus. Focusable elements can
vary between browsers, but form controls can always get focus so are
reasonable candidates for this event type.
I moved my return-key listener to an anchor tag, which on IPad is treated as a 'focusable element' similar to form controls.
I'm building my first application where I have to have compliance with keyboard navigation for accessibility reasons.
My problem has to do jquery-ui modal dialog boxes. If the user presses tab on the last control of the dialog (cancel button for this app), focus goes outside of the dialog box. Or presses shift-tab on the first control in the dialog box.
When the user does this, it isn't always possible to tab back into dialog box. IE8 and FF8 behave somewhat differently in this respect. I've tried to capture the tab key with the following event handler -
lastButton.keydown(function (e) {
if (e.which === TAB_KEY_CODE) {
e.stopPropagation();
$(this).focus();
}
});
But this doesn't work as it appears the browser processes the key press after jquery is done.
Two questions -
For Accessibility compliance, do I even have to worry about this? Although, for usability reasons, I think that I should.
Is there a way to make this work?
My problem has to do jquery-ui modal dialog boxes. If the user presses tab on the last control of the dialog (cancel button for this app), focus goes outside of the dialog box. Or presses shift-tab on the first control in the dialog box.
... and then tabbing occurs below the modal box, under a grey semi-transparent layer with scrollbar jumping from bottom to top after a few keypresses? Yes, this is a concern for sighted users who use the keyboard to browse and won't know how to go back to the modal box without pressing Tab a hundred times. Blind people won't even know the modal box is still displayed (they still can see/hear the entire DOM with their screen reader!) and that the page/script is waiting for a submit or cancel decision so it's also a concern for them.
An example done right is shown at http://hanshillen.github.com/jqtest/#goto_dialog (click on Dialog tab, direct link with anchor doesn't work :/ ). It'll tab forever inside the modal box till you click on Close or OK and will put you back on the focused element that triggered the modal box (I think it should focus the next focusable element after leaving the modal box but nevermind, this isn't the biggest accessibility problem here).
This serie of scripts is based on jQueryUI and are highly improved for keyboard and ARIA support and any accessibility problem that could exist in the original scripts. Highly recommended! (I tried to mix jQuery UI original scripts and these ones but didn't manage to get anything working, though you don't need to do so: these scripts work fine by themselves)
Maybe you should prevent the default action with preventDefault() instead of stopping the propagation and use keypress instead of keydown.
In this way there should be no need to regain focus.
Stopping the propagation doesn't work because it just prevent the event from bubbling up. You could think about using stopImmediatePropagation() but i think that changing input on the pression of the tab can't be stopped that way and preventDefault() is more correct.
lastButton.keypress(function (e) {
if (e.which === TAB_KEY_CODE) {
e.preventDefault();
}
});
fiddle here: http://jsfiddle.net/jfRzM/
Im a little late to the party, but I found I had to call preventDefault in the other keyboard events as well.
ex) I was setting the focus in the keyup event. But the browser was still doing its thing in either keydown or keypress. So I had something like this (I used JQuery/Typescript, but the idea should translate to about anything):
elem.keyup(this.onDialogKeyPress);
elem.keydown(this.onDialogPressPreventDefault);
elem.keypress(this.onDialogPressPreventDefault);
...
private onDialogPressPreventDefault = (e: KeyboardEvent) => {
const keys = [9, 27];
if (keys.includes(e.which)) {
e.preventDefault();
return false;
}
}
private onDialogKeyPress = (e: KeyboardEvent) => {
// Tab
if (e.which == 9) {
e.preventDefault();
// Do tab stuff
return false;
}
// Esc
else if (e.which == 27) {
e.preventDefault();
// Do Esc stuff
return false;
}
}
I have an input field that I would like to validate on when the user either presses enter or clicks away from it, for this I use the events keypress and blur. If the input fails validation, an alert box is called.
I noticed that in IE (all versions), if I press enter with invalid input, for some reason both the keypress and blur events are fired (I suspect it's the alert box, but it doesn't do this on FF/Chrome) and it shows two of the same alert box. How can I have it so only one is shown?
EDIT: In FF/Chrome, I now noticed that a second alert box appears when I click anywhere after I try to validate with enter.
Simplified code:
$("#input-field").keypress(function(event) {
if (event.keycode == 13) {
event.stopPropagation();
validate();
return false;
}
});
$("#input-field").blur(function() {
validate();
});
function validate() {
if ($("#input-field").val() == '') {
alert("Invalid input");
}
}
EDIT: Ah-ha. Not really a fix but a separate detail I forgot - I need to restore the invalid input to its previously valid value, so when the validate function checks the value again it doesn't fail twice.
I ended up just checking for an IE UserAgent and skipping the keypress event for IE (binding keypress and blur to the same function, as below). Not a direct or terrific solution, tragically, but I've been looking to solve the same problem to no avail. Some minor notes that might be helpful: jQuery normalizes which, so you can confidently use e.which == 13 with keypress. I'd also combine the functions into one bind, e.g.
$("#input-field").bind('blur keypress', function(e) {
if(e.which == 13) {
// keypress code (e.g. check for IE and return if so)
}
validate();
});
I've tried setting globals and using jQuery's data() to assign arbitrary flags to indicate whether (in your case) validation has already been triggered for the element, but the events trigger simultaneously or at least, if sequentially, rapidly enough that even with an opening line setting some flag to true did not do the trick. I'd read that putting in a tiny callback delay might help, but that is hella dirty and I wouldn't do it even as a workaround so I've not tested it. stopPropagation() and preventDefault() also did not help.
Firefox does not get the keypress event right. Those events are only triggered when a key combination that produces a character is pressed (which is not the same as pressing any key).
Use keydown instead (as this is probably the only event IE handles correctly - as it should, since MS "invented" it ;-) ).
See http://www.quirksmode.org/dom/events/keys.html.