I have a webapp which will be viewed using certain popular browsers and I am required to support the handling of certain keypress events. Our users will be using Windows and the keypress events always use the Alt key as a modifier.
There is no specific requirement for keyUp/keyDown event handling, the user just has to feel like something happens when he/she presses, for example, Alt-F.
How do we accomplish this in the Firefox browser, which we are required to support?
The problem:
All of our implementation attempts are interfered-with by the fact that when the FireFox menu bar is visible (File, Edit...), pressing an Alt key combination which is already claimed by the menu bar (example: Alt-f) will cause the appropriate menu to expand. We don't want this to happen. I have been shown examples of web apps (using tens of thousands of lines of javascript....) that do NOT experience this issue, so I know it is possible, but I don't know how this was done in the example I've seen with my own eyes.
I can find dozens of examples on the web of how to write an alt-key handler in JS, but I haven't found a single article on this issue or a single code example that works under the circumstances I've described. We are using Spring-MVC and a recent version of jQuery, if that matters.
I'm happy to update the question with any other information that proves relevant.
Side note about work-around suggestions:
The requestor has specifically demanded that I use the Alt key as the modifier, on the grounds that they use other webapps in FireFox where both the menu-bar is visible AND alt key combinations work. (Example: Alt-s). So, feel free to post well-intentioned work-arounds in the comment section if you wish - I promise that my own personal curiosity will drive me to read them all - but also keep in mind this is not the subject of my question.
Be aware that some browsers will not allow you to capture certain shortcuts! A working example in native Javascript for the Alt+s shortcut in Mozilla Firefox (version: 51.0.1, Linux):
window.onkeydown = function(e){
if(e.altKey && e.keyCode == 83){
e.preventDefault();
alert("Shotcut Pressed")
}
}
Hotkeys have been done well by various projects, such as jquery.hotkeys. You can see a working example on their demo page for most hotkeys. It's very small, only about 200 lines.
Here is a small example with the Alt+S hotkey that works for me (without triggering the history menu) in Firefox 40.0.2 (when the page is in focus of course, not the codepen editor).
$(document).bind('keydown', 'Alt+s', function() {
$('body').append('Alt+s was pressed; ');
// alert('alert will cause the menu to activate, do not use');
return false;
});
Related
In researching my Super User question How can I selectively disable paste blockers I discovered that the specific site I had a problem with did not appear to use any of the methods any of the existing solutions expected.
While the global solutions of using the dom.event.clipboardevents.enabled preference or Disable clipboard manipulations plugin in FireFox worked, they also also suffer the problem that there are legitimate reasons why websites might want to hook into onpaste (such as google docs rich text support or facebooks link handling) so I don't want that functionality completely disabled.
The solutions we have found (such as Derek Prior's Re-enabling Password Pasting on Annoying Web Forms and the improved Re-enabling Password Pasting on Annoying Web Forms (v2) by Chris Bailey) which use bookmarklets to selectively disable the functionality of paste blocking code don't appear to work with this page.
This makes me wonder, how does the petplanet website disable paste, why don't the existing solutions work with this site, and what other ways are there to prevent paste blocking? Answering these questions should help us write a comprehensive bookmarklet solution, so this pernicious practice can be worked around for good.
You can jQuery paste event to listen for the event and use prevenrDefault() to prevent the event.
In this page , they used the below jQuery
$('#pwd, #pwd2').bind('paste',function(e){
e.preventDefault();
alert('Please type your password.')
});
Open Firebug, Go to Scripts Tab, then search the string Please type your password. (Firebug Search Bar , not browser search bar.) , you'll find above code. And Code is present logon.asp
To Disable it , you simply use off method like this $('#id1').off(). this unbinds all events for the element that has id='id1'
As far as I know, you can only 'disable' such things with JavaScript.
As I can imagine not really the answer you are looking for, you could do something like this:
var keys = [];
window.addEventListener("keydown",
function(e){
keys[e.keyCode] = true;
checkCombinations(e);
},
false);
window.addEventListener('keyup',
function(e){
keys[e.keyCode] = false;
},
false);
function checkCombinations(e){
// try and prevent cntrl+v (paste)
if(keys["v".charCodeAt(0)] && e.ctrlKey){
alert("You're not allowed to paste");
e.preventDefault();
}
}
Source: Get a list of all currently pressed keys in Javascript
I am a beginner in Javascript & HTML5
Suppose I have a contenteditable <div> [block-level] element in my HTML5 window.
What is the exhaustive list of JavaScript events which the user could trigger by modifying this element (or some sub-elements) through user interaction?
How should I code in JavaScript to reject some user action? or change the DOM... (i.e. replace some TextNode with e.g. some <span>)
It seems that the input event cannot "undo" or "reject" some user action...
FWIW, at this point I only care about recent Firefox browsers (mine is 21 beta 7 on Linux).
This is an answer to a related question.
In other words, I don't have a clear picture of how to design rich text editors in HTML5 & JavaScript.
PS I want plain JavaScript, not interested in any library above it yet.
Addenda
Maybe mutation observers could be relevant?
Follow-up question here...
The exhaustive list of events on contenteditable elements is the same as for input type=text. See this list of all events (look especially at Form Events): http://www.w3schools.com/tags/ref_eventattributes.asp
"How should I code in Javascript to reject some user action?"... just put "event.preventDefault()" at the beginning of an event listener for the event of that action. Example to reject keypresses:
contenteditableElement.addEventListener('keypress', function (e) {
e.preventDefault();
// do something else, maybe...
});
To undo a user's action:
document.execCommand('undo', false, '');
As to designing rich text editors, there are many good demos available. I recommend:
https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla
http://www.quirksmode.org/dom/execCommand/
Make sure to view source of the last link; especially the buttons.js file. Also check out the amazing commands list on the MDN article. Good luck -- but try not to re-invent the wheel. There are many well-tested editors out there; check out this list: http://www.webdesignerdepot.com/2008/12/20-excellent-free-rich-text-editors/
We're developing several widgets, and have a requirement that we must support keyboard navigation (accessibility).
We've added keyboard navigation as to the spec, and all is well, but we also want to test that it works using unit tests.
What we have tried is testing it with
selenium, but selenium does not seem to record arrow keys
busterJS, using the solution given in thread Simulate left and right arrow key event with javascript. But here we get different exceptions indicating that we are doing something illegal.
Triggering the event using jQuery trigger(), with the same results as the previous attempt.
I can understand that fireing keyboard events with key codes can be viewed as dangerous by browser manufacturers, and thus prohibited (If thats the core problem here). If this is actually the case, is there some option to set in IE10, Chrome or Firefox to enable the possibility to fire the events?
Any comments are welcomed, I might also be looking in the completely wrong direction here, so if you have some thoughts on how to unit test keyboard navigation in javascript, please feel free to enlighten me :)
Well some solutions turned up,
The old saying "when the user says nothing has changed, asume he is lying" turned out to be truthy once again. I retested the solution in the "Simulate left and right arrow key event with javascript" thread, and doing it exactly as the solution there described worked (except IE10).
To make it work in IE10, I needed to switch the order of the if tests in the solution, because IE10 obviously only supports document.createEvent(), even though document.createEventObject evaluates to true.
I also found a solution for Selenium.
Even though selenium does not record the arrow key navigation, you can specify a keyDown command, set an element locator as your target and the escaped keyCode as your value (\37 = left, \38 = up, \39 = right, \40 = down)
How to specify selenium element locators is described in the Selenium documentation
For both solutions to work, you need to attach the elements you want to use for your test to the DOM.
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'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.