Form event incompatibilities between browsers, how to address? - javascript

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) {
}
});
});

Related

Alt-s Javascript event handler in Firefox: How?

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;
});

Custom autocomplete arrow control

I am trying to make custom autocomplete input (I know about jQuery UI autocomplete, but I decided to write a simple one). Everything went fine, I did all the 'general' stuff - sending data to some PHP script, receiving suggestions. Then I enabled choosing an element on a mouse click, and also did some navigation using down arrow, up arrow and enter keys. But I got stuck with an ambition to enable 'holding down\up arrow key' navigation (flicking through). A handler on my input listens for keyup event, and I perfectly understand that all I want is keypress event, because it maintains key hold. But keypress only works for printable characters which doesn't include down arrow\up arrow. So the question is: how can I make it work without keypress, or can I somehow override this event's maintained keys?
Thanks everybody, I've found the solution. Although keypress is meant to be fired only on printable characters, latest Opera and Firefox 5 do support it. But Chrome (and probably Safari, as they are quite similar) doesn't, whereas keydown gives the result I need.
If there is no way to overcome the keypress difficulty try something like this. This is pseudocode I didn't do all the keycode detection.
var keyStop
onkeydown = function(){
keyStop = setInterval(function(){scrollDown()},250);
}
onkeyup = function(){
clearInterval(keyStop);
}
If you for some reason got stuck in your development, I would recommend Better Autocomplete, which is a lightweight jQuery plugin which is easy to customize.

Scan inputs with Opera Mobile 10

We have chosen the Opera Mobile for one PDA application, everything went well until we hit a problem with regards to taking a scanned input to one of the text fields.
The general way you'd approach this problem is by setting one textBox to have focus when the scan operation is performed.
UNFORTUNATELY, intentionally or unintentionally Opera is not supporting this. The focus is no-where when you enter in to the screen and there is no way of explicitely setting it. Worst comes next, you cannot detect the key-press events too, which makes it virtually impossible to take the input event from the scan operation.
I have no clue why Opera, one of the best acclaimed mobile browsers, does not support this.
These are the places the same question is asked over and over again,
http://dev.opera.com/forums/topic/255066
http://dev.opera.com/forums/topic/650332
http://dev.opera.com/forums/topic/384311
We have posted in the Opera Dev forum as well and it seems that they (so far) have no solution for this. If anyone has tried a workaround, we would be interested to hear the solution.
And please note that the solution in here is not working in Opera Mobile 10. I have not tried it in the proposed 9.X version.
I found it myself. And here is how to do it.
Have a hidden button in the form
input type="button"
id='myHiddenButton' visible='false'
onclick="javascript:doFocus();"
width='1px' style="display:none"
Have a javascript to get fired on the click event of the hidden button.
function doFocus() {
var focusElementId = "MyTextBox"
var textBox = document.getElementById(focusElementId);
textBox.focus();
}
Have the button clicked using a javascript at the end of the document
function clickButton() {
document.getElementById('myHiddenButton').click();
}
setTimeout("clickButton()", 100);

Best way to capture all key events for a web application?

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.

Javascript Events: Getting notified of changes in an <input> control value

I have the following problem:
I have an HTML textbox (<input type="text">) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).
I want to be notified in my script every time the value of that textbox changes, so I can react to it.
I've tried this:
txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.
Is there another event I can listen to, that i'm not aware of?
I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com)
As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
myListener(year,month,day);
return orig(year,month,day,hide);
});
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.
addEventListener("DOMControlValueChanged" will fire when a control's value changes, even if it's by a script.
addEventListener("input" is a direct-user-initiated filtered version of DOMControlValueChanged.
Unfortunately, DOMControlValueChanged is only supported by Opera currently and input event support is broken in webkit. The input event also has various bugs in Firefox and Opera.
This stuff will probably be cleared up in HTML5 pretty soon, fwiw.
Update:
As of 9/8/2012, DOMControlValueChanged support has been dropped from Opera (because it was removed from HTML5) and 'input' event support is much better in browsers (including less bugs) now.
IE has an onpropertychange event which could be used for this purpose.
For real web browsers (;)), there's a DOMAttrModified mutation event, but in a couple of minutes worth of experimentation in Firefox, I haven't been able to get it to fire on a text input when the value is changed programatically (or by regular keyboard input), yet it will fire if I change the input's name programatically. Curiouser and curiouser...
If you can't get that working reliably, you could always just poll the input's value regularly:
var value = someInput.value;
setInterval(function()
{
if (someInput.value != value)
{
alert("Changed from " + value + " to " + someInput.value);
value = someInput.value;
}
}, 250);
Depending on how the external javascript was written, you could always re-write the relevant parts of the external script in your script and have it overwrite the external definition so that the change event is triggered.
I've had to do that before with scripts that were out of my control.
You just need to find the external function, copy it in its entirety as a new function with the same name, and re-write the script to do what you want it to.
Of course if the script was written correctly using closures, you won't be able to change it too easily...
Aside from getting around the problem like how noah explained, you could also just create a timer that checks the value every few hundred milliseconds.
I had to modify the YUI datable paginator control once in the manner advised by Dan. It's brute force, but it worked in solving my problem. That is, locate the method writing to the field, copy its code and add a statement firing the change event and in your code just handle that change event. You just have to override the original function with that new version of it. Polling, while working fine seems to me a much more resource consuming solution.

Categories

Resources