Capturing key event for backspace - javascript

I am having difficulty capturing the backspace key as a keyboard Event in javascript/jQuery. In Firefox, Safari, Opera, Chrome, and on the iPhone/iPad, I capture a keyup event on a text input box like this:
$(id_input).keyup(function(event) {
that.GetHints($(this).val().trim(), event, fieldName);
});
This event captures user keystrokes, then sends them to a function to issue an ajax lookup call.
My problem comes when a user wishes to backspace over a character he/she already typed. In all the browsers to which I have access except for my Droid phone, when I press the backspace key, this keyup event captures the value returned by $(this).val().trim() and sends it on to process in function GetHints. On the Droid, however, neither this keyup nor an equivalent keydown event fires until the user backspaces over every character in $(this).
So, for example, if I type "cu" then backspace over the "u" leaving only "c" in the input field, in all browsers except Droid, the keyup event will fire and call function GetHints("c", event, fieldName). On the Droid, the keyup event never fires.
What am I missing? How/why does this backspace key, on either the soft keyboard or the hard keyboard, on my Droid not function as expected? How do I work around this?

You could poll for changes in the text (using setInterval). This would probably be more reliable. For example, keyup wouldn't fire if the user does right-click -> cut. Polling alone would be less responsive, but you could combine it with keyup to keep it snappy. Polling would be a bit more processor heavy.
Try something along these lines:
var oldText = '';
var timer = setInterval(function(){
var text = $(id_input).val().trim();
if(text != oldText){
oldText = text;
that.GetHints(text, fieldName);
}
}, 500);
Tweak the interval duration as necessary.
I'm not sure what that.GetHints does with event, but obviously, you wouldn't be able to pass that in using the polling approach (because there isn't an actual event being fired). Is this a problem?
You can use clearInterval(timer); to stop polling if you want to.
You could keep your existing keyup function as it is (to increase responsiveness). Alternatively, you may wish to just poll to avoid that.GetHints being called too much (e.g. if someone types something in really quickly).

Related

How to handle keyboard "Done" button in iphone safari browser using JavaScript [duplicate]

I'm wondering if there's a way to capture the iPhone's virtual keyboard's done button event, using JavaScript?
Basically, I just want to be able to call a JS function when the user clicks done.
I was unable to track the 'done' button being clicked. It didn't register any clicks or keypresses. I had to addEventListeners for change, focusout and blur using jquery (because the project already was using jquery).
You need to do some kind of this:
$('someElem').focusout(function(e) {
alert("Done key Pressed!!!!")
});
It worked for me, hope it will help you as well.
After searching and trying this solution
basically is say:
document.addEventListener('focusout', e => {});
tested on IPhone 6s
This question is kinda old, but I've found a hacky way recently to make this working.
The problem with the 'blur', 'focusout' events is that they fire even if user just tapped outside the input/textarea, and did not press the 'Done' button, in my case, UI should behave differently depending on what exactly have happened.
So to implement it, I've done the next thing:
After showing the keyboard (the input received the focus), add click handler on the window via the addEventListener function. When user clicks on the window, remember the timestamp of the click in the variable (let's call it lastClick = Date.now())
In the blur event handler, set a timeout for 10-20 ms to allow other events happening. Then, after the timeout, check if the blur event happened in a time difference lower for example than 50-100 ms than the lastClick (basically Date.now() - lastClick < 50). If yes, then consider it as a 'Done' button click and do corresponding logic. Otherwise, this is a regular 'blur' event.
The key here is that tapping on keyboard controls (including Done button) does not trigger the click event on the window. And the only other way to make keyboard hide is basically tap on other element of the page and make the textarea lose focus. So by checking when the event happened, we can estimate whether that's a done button click or just blur event.
The answer by oron tech using an event listener is the only one that works cross platform.
document.getElementById("myID").addEventListener("focusout", blurFunction);
function blurFunction() { // Do whatever you want, such as run another function
const myValue = document.getElementById("myID").value;
myOtherfunction(myValue);
}
"Change" event works fine
document.querySelector('your-input').addEventListener('change',e=>
console.log('Done button was clicked')
);
attach a blur event to the text box in question. The done fire will fire this event.
The done key is the same as the enter key. So you can listen to a keypress event. I'm writing this using jQuery and i use it in coffee script so I'm trying to convert it back to js in my head. Sorry if there is an error.
$('someElem').bind("keypress", function(e){
// enter key code is 13
if(e.which === 13){
console.log("user pressed done");
}
})

Clearing the value of a text box after the enter key has been pressed

I've created a site/game for school with a text box. It looks a little like Quizlet (https://quizlet.com).
When the users presses the enter key, the input should be cleared. The problem is: On the computer, it works just fine but on a phone, it leaves an empty line. So the word checker always counts it wrong unless the player removes it with the backspace. Is there a way to remove the enter on a phone? Because I'm having a lot of trouble with it (especially because it's kind of necessary that it works on a phone).
// The code I used a year ago to
resetInput();
function resetInput() {
document.getElementById("input").value = ""; //
document.getElementById("opmerking").innerHTML = "TextBalk geupdate!";
}
Edit
I found the solution, the problem was that I called an 'onkeypress' event, which can fire before the key is released, meaning the input is cleared, and after that, an enter is placed. I fixed it by using the onkeyup event, and canceling this event when the pressed key was the enter key.
The solution was the timing in the events.
I called an 'onkeypress' event, which fires before the key is released, meaning the input is cleared, and after that, an enter is placed. I fixed it by using the onkeyup event, and canceling this event when the pressed key was the enter key.

in google search box which event fire?

in google search box when we typing something , On that time some auto complete result coming after select any one it automatically fire no need to
focusout()
or
any click()
how it create
There are basically three key related events keydown, keypress and keyup, it is using combination of these events... To make you understand more here is the detail
keydown is fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrl is held 'down'.
keyup is fired when the key is released (including modifier/etc keys)
keypress is fired as a combination of keydown and keyup, or depending on keyboard repeat (when keyup isn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!) If user keep key pressed, then this event is fired for every character added by the browser.
NOTE: Remember one thing, if you are fetching the value from the field never ignore the keyup event, because while getting text of the input you won't get the last type character from the textfield until keyup event is fired...
See this fiddle to get more idea about key events..

How to display only one key if i hold the key down in the textarea

Is There any possible way to display only one character when a key is pressed DOWN for a longer period of time what I mean is when I press lets say 's' DOWN for a longer period of time I want only 's' displayed and I don't want this to happen 'ssssssssssssssssssssssssssssssssssssssss....' .
And whit out using this method because this brings on the problem that if a user types fast and presses two keys at the same time only the second one will get displayed for example if I press down 'k' and press down whit out letting 'k' go the 'p' only the 'p' will get displayed.
var textarea='';
document.getElementById('textareaID').onkeydown=keydown;
document.getElementById('textareaID').onkeyup=keyup;
function keydown () {
this.value=textarea;
}
function keyup () {
textarea=this.value;
this.value=textarea;
}
And please do not say using counters because it doesn't work for some reason believe me I have tried for the last 3 days.
http://toki-woki.net/lab/long-press/ this is what i am basically trying to do but I cant understand how the part where you hold the key down and only one is displayed out is done and of course if i press a key and while the key is down i press another one both of them get displayed rest is easy.
So i would love and explanation its driving me crazy.
Alright I think I got it.
1: On keydown cancel the input to the textarea.
2: On keyup put in the clicked letter.
document.getElementById('textareaID').onkeydown=keydown;
document.getElementById('textareaID').onkeyup=keyup;
// keydown is run more than once if held down hence "ssssssss"
function keydown (event) {
// cancel input
}
// since the keyup event is only fired once we will do most of the work here
function keyup (event) {
// insert input
}
Here is the code (there are comments so you can see what's going on):
http://jsfiddle.net/NerfAnarchist/gXVuC/
As commenter PA pointed out, I think this is bad practice to alter native behavior of textbox or textareas. See your other options before doing this.
...But IF you have to do it:
You can use the keyDown event to let the event pass on condition that it is followed by a keyUp event. The following code is based on this fiddle.
​document.getElementById('box').addEventListener('keydown', function(event){
// Superglobal window.characterPrinted to detect if the event has already fired.
if(window.characterPrinted != true){
window.characterPrinted = true;
this.value += String.fromCharCode(event.keyCode);
event.preventDefault();
}
})​​​​​​​​;
document.getElementById('box').addEventListener('keyup', function(event){
// Reset superglobal
window.characterPrinted = false;
});
Note that this code uses addEventListener and preventDefault, which is not guaranteed to work in older browsers. You'll need to bind events using different methods. (I'm looking at you, IE7).
Another note: this code adds to the textarea. Therefore, if a delete key pressed, it will try to add a delete, which does nothing. You can do an event.keyCode filtering to see if it's a letter before fiddling with the event itself, much like Michael suggested.

jQuery keyboard events

Using jQuery, I would like to capture a keyboard event that is:
before the user lifts their finger from the key
after the characters from the keyboard event have registered in the input box.
To clarify, view this example. When keypress fires, the input value has not been updated yet.
[Edit]
Apparently I wasn't clear as to what I need.
The function must be called before the user lifts their finger up from the key, but after the key's character is placed in the input box. So the following do not work:
keydown: at the keypress event, the value in the text box has not been updated
keypress: at the keypress event, the value in the text box has not been updated
keyup: this is called when the user lifts their finger, which is too late.
You can use the input event, which works in recent versions of all major browsers:
var input = document.getElementById("your_input_id");
input.oninput = function() {
alert(input.value);
};
Unfortunately, it doesn't work in IE <= 8. However, in those browsers you can use the propertychange event on the value property instead:
input.onpropertychange = function() {
if (window.event.propertyName == "value") {
alert(input.value);
}
};
SO regular JavaScript answerer #Andy E has covered this in detail on his blog: https://web.archive.org/web/20140626060232/http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery
Use keyup event, an example on jsFiddle
$("textarea").keyup(function(e){
alert($(this).val());
});
It happens after you lift the key. I don't know what you want to achieve, but you can store the state before lifting the key (on keydown or keypress) and restoring later if needed. You also can stop the output in the keyup event using e.preventDefault(), so even after the key is up it will not register the values in the area.
You could listen on keydown event and store the value in a variable. That variable would have the value as it was before the new input, and the new input would be included in the keyup event
UPDATE:
Ok, I misunderstood your requirements, but there isn't an event that would meet your needs. The only thing I can think of to simulate this behaviour is the following:
listen on keydown/keypress
get the value from the event object (get event.which, then convert it to actual value)
use a variable like I mentioned in the original advice and concatenate the new input to it
Here is a fiddle: http://jsfiddle.net/HpXuU/13/
This is obviously not a perfect solution, as it needs some (one might argue unnecessary) work to get done right. I would advise to rethink your needs, but if this behavior is absolutely what you need, I think this is a step in the right direction.
You can use setTimeout:
$('input').keypress(function() {
var that = this;
setTimeout(function() {
// read that.value
}, 0);
});
Live demo: http://jsfiddle.net/HpXuU/8/

Categories