I have some custom web components in my mobile web app, whereas I need to manually fire 'focus' events on a field, to simulate the 'NEXT' functionality in the Android soft keyboard feature. ( using Galaxy S3 native browser ).
However, when I manually fire a focus event on a 'select' field, the native soft keyboard does not show. I have to subsequently click on the field to get it to show. (In IOS, of course, it works just fine).
So I'm wondering, if a 'focus' event doesn't trigger the soft keyboard to open, what JS event will ???
I am not using phonegap so I'm hoping there's a way without it.
Thanks for any help!!!
Here's a link from StackOverflow:
Showing Android's soft keyboard when a field is .focus()'d using javascript
Just focussing without an event doesnt seem to work. - you DO need a
click event triggering this.
$(document).ready(function() {
$('#field').click(function(e){
$(this).focus();
});
$('#button').click(function(e) {
$('#field').trigger('click');
});
});
You can do this by calling focus() then click() on the input. No need for jquery. Beware of endless loops if your script is triggered by an onclick() on a containing element. Make sure as well that this script is triggered by some user interaction. It won't work from document.onload(), or from a setTimeout(). It's also fragile with things like simultaneous style changes on the elements. The script below is working for me on Chrome for android 58 and Safari mobile 602.1.
var target = document.getElementsByTagName("input")[0];
if (event.target != target) {
target.focus();
target.click();
}
Vanilla JS solution:
let button = document.getElementById("b");
let input = document.getElementById("i");
// Keyboard opens when focusing the input from a click listener
button.addEventListener("click", () => {
input.focus();
});
// Input field gets focus but keyboard doesn't open.
setTimeout(() => {
input.focus();
}, 1000);
Related
I am trying to intercept "Hide keyboard button" specific for Ipad in Javascript. I searched everywhere but could not find correct keycode for that.
I pressed any keys and I get a keycode map (for characters, but also for enter, space and delete..).
This is an example of what I want to accomplish
$( "#mydiv" ).on( "keydown", function( event ) {
if (event.which == xx){
//do something
}
}
where xx is my keycode on 'hide keyboard button'. No method is called to the delegate when the button is pressed nor a KeyCode.
I took a look at detect iPad keyboard Hiding button, but I get a solution on a different level (with Xcode), but I need a solution with Javascript.
Hope someone could help.
I found a workaroud for iPad IOS7. I will test on IOS8 to make sure it works. So basically I create a listener on every FOCUSOUT event (for all my texts) and I call my function.
It fires when you have your keyboard open and when you close your "keyboard". It doesn't fire when you select another text field or button, because it targets on null. If you use in combination with keydown, you can save multiple value and call your submit function only when you release your keyboard.
It works for my specific project.
document.addEventListener('focusout', function(e) {
if (e.relatedTarget === null) {
alert("close keyboard without click on something else");
callYourFunction();
}
});
p.s
I'm pretty new here in SO, so I don't know if I can reply myself or I should edit my question or make a comment.
I have a simple detection if a software keyboard is opened on Android and iOS:
$(document).on({
focus: function() { keyboardOpened = true; },
blur: function() { keyboardOpened = false; }
}, 'input'); //catch all focus and blur events fired on any input element
It's used to prevent certain actions while user is writing a message (e.g. ignoring resize events).
It works on all browsers except for Chrome on iOS. I've included Firebug Lite on the site but there is no error, just the events are never fired and the web does not work correctly when opening SW keyboard.
Here is a fiddle: http://jsfiddle.net/WYULR (click the input and see an alert)
Anyone knows about a reason or workaround for this?
I get this too :( My solution is to detect if ipad + chrome using :
var isCriOS = /CriOS/.test(navigator.userAgent);
I tried https://github.com/gabceb/jquery-browser-plugin + webkit type distinguishing code found here How to detect chrome and safari browser (webkit) but I couldn't get that to work.
If ipad+chrome, apply a 'click' event for the field to do the same thing ... this is only good if the only focus you will have is from user taps, as calling .focus() will not trigger it ... but in this case you could just call the function ascribed through click event after the .focus() . This seemed a bit hackish so I decided to test vanilla js .onfocus event and proved that it wasn't firing either.
What is the best cross-browser and cross-platform way to detect hardware keyboard presence with javascript?
This may be an old question, but a few months ago, I was looking for a solution to this myself. I was building a messaging system which should send the message when someone hits Return on their physical keyboard, but inserts a newline when someone hits Return on a virtual keyboard. The way I solved it was by counting the time between keydown and keyup events and getting the average when Return was hit.
I finally got around to documenting it on my blog here.
Could you try the theoretical opposite? Instead of trying to detect keyboard hardware, why not try to detect a touch screen? With the ontouchstart event;
if ('ontouchstart' in document.documentElement) {
// show icon
}
Keyboard in JS is accessible via browser APIs which delegate to OS APIs and it's not possible to tell if there's a physical keyboard. I can cut the cord off of my physical keyboard right now, turn on virtual keyboard, click on the on-screen buttons with my mouse and the browser will still trigger every keyboard event the scripts are listening to. Form browsers's/JS's perspective the virtual keyboard is indistinguishable from a physical one.
And what does "presence" even mean? If I have a phone with a touch screen and slide-out keyboard do you expect the browser to trigger some kind of "keboardIn"/"keyboardOut" event? Same with cable plug-in/out? :)
If your app absolutely requires a physical keyboard just inform/ask the user.
Edit - after clarification by OP:
You know the facebook chat? You send messages simply by pressing
"Enter", I have to show users that do not have a keyboard button to
replace the "Enter" key.
So just make a form with text input and listen to the input/form events. Most (every?) soft keyboards have some kind of "Done", "Ready" or similar button. You don't need to know if the "keyCode" is equal to "13", but detect that the user has an intent to submit what he has typed. Or, as the last resort, detect f the device i touch-enabled and display the button then. ( if('ontouchstart' in document.documentElement)/* show touch sbmit button */ )
Use keyboard event to detect if the user have keyboard or not (he/she may press it). Save it in localStorage and the browser will remember it for the next time.
var app = this;
app.hasKeyboard = false;
this.keyboardPress = function() {
app.hasKeyboard = true;
$(window).unbind("keyup", app.keyboardPress);
localStorage.hasKeyboard = true;
console.log("has keyboard!")
}
$(window).on("keyup", app.keyboardPress)
if(localStorage.hasKeyboard) {
app.hasKeyboard = true;
$(window).unbind("keyup", app.keyboardPress);
console.log("has keyboard from localStorage")
}
When a virtual keyboard pops up on the screen on a mobile device, the height of your application reduces in order to accommodate the virtual keyboard. So, what you can do is that you can add an event listener that checks whether the screen has resized as the user focuses on the input field.
You can add this functionality using the resize event listener when the input field is focused:
const inputField = document.querySelector(".my-input");
const virtualKeyboardDetected = () => alert("Virtual keyboard detected!");
inputField.addEventListener("focusin", () => {
window.addEventListener("resize", virtualKeyboardDetected )
})
inputField.addEventListener("focusout", () => {
window.removeEventListener("resize", virtualKeyboardDetected )
})
if (confirm('Do you have hardware keyboard?')) {
} else {
}
Edit according to description in comments under question:
What about support 'Enter' everytime and add 'Send' icon only for touch screens (What's the best way to detect a 'touch screen' device using JavaScript?) and as a 'hover' pseudoclass for mouse?
Is there some way to find out what caused the onChange event on select box in Internet Explorer (>= IE8) - keyboard or mouse?
I have a code which doing something when user selecting a value, and this code works great in Firefox and Chrome but not in IE (no surprise, huh). In IE it works fine only if user uses mouse but not a keyboard, because then it fires a onchange event on every keypress (not on Enter as normal browsers).
So, to fix this behavior I need to know if event is fired using a keyboard and then I will filter it.
Update:
Ok, after playing a bit I found a good solution. Posting it here in case someone will find it useful. Solution below using jQuery but it can be done in pure Javascript too.
This is a code which caused a problem:
$("#mySelectBox").change(function () {
// Do something
});
And this is my solution. It's probably not perfect, but it works in my case. And event handlers could be chained in jQuery, of course. The code below stores initial value of the select and uses it to avoid doing something on initial mouse click - when user expands a select box. Also it filters all keypresses except Enter.
function doSomething(el) {
if (el.data["valueOnFocused"] !== el.val()) {
// Do something
}
}
$("#mySelectBox").focusin(function () {
$(this).data["valueOnFocused"] = $(this).val();
});
$("#mySelectBox").keyup(function (e) {
if (e.which === 13)
{
doSomething($(this));
}
});
$("#mySelectBox").click(function () {
doSomething($(this));
});
Basically the onchange event is supposed to be fired when the user makes a selection then leaves the input (be it select, textbox, radio button, whatever). Since this isn't working in IE, you could try using onblur instead, to detect when the user actually leaves the box. At that point you could read which item is selected and act accordingly. This is more of a workaround, but might do what you need.
Edit: another option would be to detect the pressing of the Enter key, like so:
if(e && e.which){ // NN4 specific code
e = e
characterCode = e.which
}
else {
e = event
characterCode = e.keyCode // IE specific code
}
The characterCode variable now has the "code" of which button was pressed. If it was the enter key, that code will be 13. You could listen for this.
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");
}
})