I'm a little distraught at the current state of key capturing for web applications. It works great as long as you know your user is going to be typing in a specific place (e.g. an input field), but as soon as you want to do global shortcuts for an entire "application", it seems to fall apart.
I'm trying to find out if there is a better way to capture all the key events for a web page than the method I am currently using.
My current method is to use the JQuery Hotkeys plugin, bound to the document element, i.e.:
$(document).bind("keyup", "delete", function() {});
That works great for most purposes, but for example on Firefox, if the user happens to absentmindedly move their mouse over the navigation bar, the delete key will sometimes result in the user going "back", and the key is never received by the handler so that I can stop propagation.
Is there a different element I should be binding to? Is there a better plugin out there for this? Should I just avoid using any keys that are bound to things in common web browsers?
As more and more web applications look to mimic their desktop counterparts, it seems like this is a basic feature that web developers will increasingly require.
EDIT: I should point out that I am already using e.stopPropagation() and e.preventDefault(). The main problem seems to be that sometimes the event is never even passed to the bound function. I am basically wondering if anyone has figured out a "higher" element to bind to other than document. Or is there an alternative I have never even thought of? Embedding an invisible Flash element on the page and then passing all keys from that to JavaScript, for example (I don't think this would work).
I think, at this point, I am doing things the "standard, well-known way." I am trying to see if there is an outside-the-box way that isn't widely known that maybe someone on Stack Overflow knows about :-).
If you are making a sophisticated web-app with customized keyboard controls, the first thing you should do is alert the user that you are making a sophisticated web-app with customized keyboard controls. After that, tell them what the controls are and what they do.
Binding the keypress and keydown listeners to the document is the correct way to do it, but you have to remember to preventDefault and/or stopPropogation for keypresses that you want to override. Even if there is no default behavior, you will need to prevent them from cascading in case the user has rebound their default keyboard shortcuts.
Also, you will only be able to receive keyboard input when the page has focus.
When you say Delete I assume you mean the Backspace key as Delete generally referrs to the key next to Insert, Home, End, Page Up and Page Down.
Edit to add:
Be very careful about which keys you choose to override. If you're making an app to be used by people other than yourself, you have to worry about usability and accessibility. Overriding the Tab, Space and Enter keys is risky, especially for people using screen-readers. Make sure to test the site blind and fix any issues that may arise with traversing the page via the keyboard.
maybe you can use html-attribute ACCESSKEY and react onfocus.
i.e.:
<input type="text" size="40" value="somefield" accesskey="F">
i think u might need to add a tabindex to tags like <div>
<div id="foo" tabindex="1" accesskey="F">
You can't bind to events that happen where you have no control - e.g. the window chrome. The way most webapps deal with this is asking the user to confirm their decision to leave the page, using the onbeforeunload event:
window.onbeforeunload = function (e) {
var str = 'Are you sure you want to leave this page?';
e = e || window.event;
if (userHasSomeUnsavedWork) {
e.returnValue = str;
return str;
}
}
onbeforeunload - MDC
Absolutly non-tested but... try it on 'window' element.
Related
I am trying to add more accessibility to my app so i've added eslint-plugin-jsx-a11y to my eslint process. This has been great, however I have a question in regards to the click-events-have-key-events rule (https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md ).
I want to add an onKeyDown or an onKeyPress anywhere I'm using the onClick in my react code. However I am not sure which keycode I should be listening to.
If, for example, I just do
<div
onClick={this.myFunction}
onKeyDown={this.myFunction}
/>
That onKeyDown function fires when i just tab away from that div. So I am thinking I need to filter keyCodes, however when trying to meed accessibility standards, I'm not sure which keyCodes I need to listen for. Is the enter keyCodes enough - do all screen readers respect this for example?
Looking for some insight into this to help make my app more accessible and screen reader friendly.
You didn't ask specifically about this but the best solution is to use a native html element if possible. See the first rule of ARIA use. Native elements have the behavior built in to the element and work great with screen readers.
However, sometimes you need to create a custom element and that's where ARIA comes in. But you need both attributes and a role to make a custom element, and additionally you need keyboard/mouse handlers if the element will be interactive.
The types of keyboard events you listen for depends on the role. For example, if you were creating your own link element, instead of using an <a>, you'd listen for the ENTER key. If you were creating your own button, you'd listen for both the ENTER and SPACE keys.
The types of keys you listen for are explained in the design patterns in "WAI-ARIA Authoring Practices 1.1". For example, see the "Keyboard Interaction" section for buttons.
Scenario:
I have an web app where I need to capture all keyed input to the page in a central location. My first solution was to continually give focus to a text box so all focus would go through there. That works amazingly for desktop browsers, but causes the undesirable effect of causing the soft keyboard on mobile browsers to always be visible. Since my keyed input is coming from an external source, I don't want the keyboard visible until I request it. Since there's no direct way (that I've found) to do this, I was trying to give constant focus to a control that doesn't cause the keyboard to show. I was unable to find a control that didn't cause the keyboard to show, but would fire one of the key events (keydown/keyup/keypress).
Does anyone have a suggestion as to how I can catch all keyed input without displaying the soft keyboard?
Note: I can have a different solution for desktop and mobile if necessary.
Any help is appreciated!
Ok, so the answer was so simple, I can't believe it took me so long to get to it.
If you make a textbox readonly, it doesn't show the keyboard, but still fires key events. This allowed me to accept input from the external source without showing the keyboard. I also added a keyboard toggle button that simply hid the readonly textbox and showed the regular one.
If my application would have been different, I could have just added and removed the readonly attribute and applied focus again to have the same effect.
Thanks for all replies, including the ones that got deleted.
var keyedinput = "";
window.addEventListener('keydown', function(event){keyedinput += String.fromCharCode(event.keyCode)}, false);
keyedinput will contain the contents of the keyed input from the external keyboard-like device. Simply reference it as a global variable when needed. If there is an enter/esc key or and "end" key (sequence?) you can just check the corresponding keyCode to launch an action with the contents of the variable instead of appending to it.
I have a textarea on a html page, on google chrome, well I don't know what version because the user interface is deviously hidden, but on chrome the onChange="code" event isn't firing but on Firefox 11.0 1.0 (according to help->about) it is firing. Then instead I start playing around with the events onkeydown="same_function()", onpaste="same_function()" and oninput="same_function()", in order to be absolutely sure to capture at least one event. But now the problem is that I'm getting too many events, and when I check the textarea_dom_object.value of the textarea after getting a keydown event the key that was pressed isn't included in the value that I'm reading; if I have "abc" in the textfield and I press 'd', that generates a keypressed, but I'm still getting only "abc", not "abcd".
Is there a compatible way, or at least a way that works on most browsers, to get an event every time a textarea changes, but preferably only one event? I don't like the kind of ugly code I would have to write if I had to first test if I've already listened to an event and so forth. All I want is one event each time the text in the textarea changes.
Here's the thing about why jQuery is so amazing. It understands the need to gracefully degrade the code between browsers that don't support newer functionality. JavaScript in and of itself does not offer this support stand alone. By enhancing JavaScript's core capabilities in using jQuery, you are generally going to be more successful with cross browser support.
That being said...
There are still plenty of scenarios where you need to identify what device/browser you're working with so that you can perform the expected operations.
The most important thing to remember is that there is no 100% cross-support library in existence.
you can do this. just make sure you give the textarea an id tag
$(document).ready(function(){
$('.addtitle').keyup(function(event) {
if(event.keyCode==13) {
}
});
});
in my case here, im firing the function on the enter key (like facebooks functions).
EDIT: also if you have more then one textarea on a page, you should do this:
$(document).ready(function(){
$('textarea[name=mynamevalue]').keyup(function(event) {
if(event.keyCode==13) {
}
});
});
I am making mouse click events and I'm trying to dispatch it to some node several times in a row. For that I am using the same MouseEvent object and for some reason this approach does not work. Yet, when I create event manually each time, system works. Does anybody know what is the reason for this behavior?
I've tried to change the timeStamp, but problem still occurs. I can solve the problem like I mentioned before, but I am interested in how this MouseEvent and corresponding dispatching and handling subsystems really work. MouseEvent specification that I've found on MDC pages seems to lack a lot of information.
Tnx for the help!
This is actually a security mechanism, dispatching an event that has been dispatched before isn't allowed. An event always has additional data associated with it, for example whether it comes from a trusted source (user's keyboard rather than JavaScript code). Some attacks (mostly against MSIE because it had mutable event objects) were using this - they caught a trusted event, changed it and dispatched it again elsewhere (changing might not always be required, dispatching it at a different element is enough for some attacks). In the end disallowing redispatching of events turned out to be the best solution. After all, this functionality isn't really required: creating a new event object with identical properties (minus hidden data) isn't exactly hard.
Pretty much all the security issues in this area were related to the file input control. Some time ago Firefox decided to change the file input UI radically and disallow entering the file name directly. I wonder whether this change made redispatching of events a non-issue. I doubt that anybody will be willing to risk opening this can of worms again however.
I think the reason you can't reuse the same MouseEvent object is because the event system maintains some internal state in the event objects so they can implement things like bubbling and cancelling. You may just have to stick with creating distinct event objects.
Reading Document Object Model Events may give you a better understanding of how the DOM event system works.
Without knowing what you have now ill just go under assumption.
Make an event function:
function clickEvent(event) {
//do something
}
Attach it:
obj.onclick = clickHandler;
And you can do this multiple times to multiple objects.
I need to send bunch of commands to the server on timer - like:
put(0,"hello")
del(4,1)
put(4," is around the corner")
so I need to monitor and record all of the user input and compile/flush it on the timeout (idle), something like macros.
I can record all things happening onKeyUp/onKeyDown/onMouseDown/onMouseUp using textarea cursor position and keys information (and make it cross-browser some time later) but I can't handle things like pasting using mouse right button and selecting 'Paste' or pasting from the menu (I can handle onChange, but I will have no information is it pasted or already recorded as pressed keys and it fires only after focus change). Even pasting from context menu fires some useful info, but the menu from the browser is the only thing, giving nothing for Javascript.
Is there any plugin for jQuery or something like that and do I really have no other ways to implement it without comparing current-document and document-a-second-before?
Upd.: There are events for handling cut/copy/paste: http://www.quirksmode.org/dom/events/cutcopypaste.html , but what about
the undo one?
P.S. I will show a macro-recording code when I'll finish, if someone really needs it. And to finish it properly, I just need the undo handling possibility. Current version is here: http://code.google.com/p/sametimed/source/browse/WebContent/module-editor.js, look for compileCommands method.
There are events for cut/copy/paste you may listen to, depending on browser. So if they are triggered you may use them, otherwise fall back to more tedious work-around.
See: http://www.quirksmode.org/dom/events/cutcopypaste.html