I have recently come across something quite wierd, I'm not sure if it's maybe me just missing something but I can't understand why this is happening.
I have a site that has the following jQuery snippet running on it:
$(window).resize(function(){
alert("Resize fired!");
});
When I go to the site on an Android phone browser, and simply scroll up and down the site, I can see the alert.
The Android browsers scroll bars (which fade in and out) are overlayed ontop of the entire site and don't seem to cause any resizing of the window, so I'm guessing this event isn't being fired by them.
Does anyone know why the Android browser is firing this event on scrolling?
Any information will be greatly appreciated.
EDIT:
I have tried setting CSS for body, setting overflow-y to scroll to see if that was a viable solution but the event is still being fired on scrolling on Android.
EDIT #2:
I am using the following metatag in my HTML:
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
I was having the same problem, my solution was to check if the window size actually changed, for doing it I needed to store the past window width somewhere in my app. The code could be something like this:
$(window).resize(function() {
clearTimeout(app.resize.timer)
app.resize.timer = setTimeout(function(){
var window_changed = $(window).width() != app.size.window_width
if(window_changed) console.log('Window size changed! resize site')
}, 500)
})
I did not count on the window height because my Android browser hides and shows the address textbox when I scroll down the site making the window height change on vertical scroll
#john-mccollum is correct in the comments. It appears to be the disappearing browser interface causing a change in height that triggers the resize event. So check for change in width specifically in your function if you are doing responsive design stuff where you want to check if the width has been resized.
$(window).resize(function(){
var w = $(window).width();
if (typeof checkw == 'undefined') checkw = w;
if (w!=checkw) {
console.log("The width changed from "+checkw+" to "+w);
// do your responsive magic!
checkw = w;
}
});
Not required to make this work, but this pairs well with the Paul Irish / John Hann "smartresize" method.
i'm having the same problem too!
the problem is true because the height of the browser in Android will change when the url bar hide and show. So, we have to make the browser reload only happens when the width size changes.
i saw this question in Stackoverflow show me how to do this. And this is the jsfiddle.
var doit;
function resizedw(appwidth){
var window_changed = $(window).width() != appwidth;
if ($(window).width() != appwidth){
("body").append("did it"+appwidth+" ");
}
past_width = $(window).width();
}
var past_width = $(window).width();
window.onresize = function() {
clearTimeout(doit);
doit = setTimeout(function() {
resizedw(past_width);
}, 100);
};
Related
I have some content/input fields that are covered when the android keyboard is shown in my cordova app. I have
android:windowSoftInputMode="adjustPan" and <preference name="fullscreen" value="false" />
I tried android:windowSoftInputMode="adjustResize but it kept shrinking my content because it was resizing the window (My content is sized based on viewport width and viewport height). Thank you for any suggestions!
So I had a work around myself that may or may not work for everyone, but I figured I could post this to hopefully help someone who comes across this!
I found a lot of answers but none really helped me. So in my AndroidManinfest.xml file I set android:windowSoftInputMode="adjustPan|stateHidden". Yes, this will still cover the content below the keyboard when it's opened.
To avoid that, I gave all of my scroll views that would be affected by the keyboard being shown a class of inputScrollContainer. Name them whatever you would like.
Since every container (for me) was the same height as was the top bar for each page, I did the following: (you will have to install the device plugin and the keyboard plugin from cordova
Got window.innerHeight at the beginning of my js (if you do this inside of your native.keyboardshow function, iOS will give you the resized view based on the keyboard's height)
Then, inside my native.keyboardShow function, I did the following:
- Then got the height of the top bar (I chose one as they were all the same)
- Added the added the keyboard height and top bar height together
- Then I subtracted those from the window height
Doing this now gave me the height "leftover" for the scroll view to have. After that I:
Got all elements by class name inputScrollContainer
Looped through them and assigned the new height to each (you can assign it to the only scroll view currently in view, but I only had three affected views so I wasn't worried about it)
Now the scroll view was resized to whatever was left between the top bar and the keyboard. Then on my native.keyboardhide function, I just restored the height to what the original height for all of the scroll views was before.
I'm sure there are other ways to do this, but doing it this way gave me flexibility and consistency across iOS and Android. I hope this helps someone!
To move the layout up when the keyboard is visible/shown add the following activity.
<activity android:windowSoftInputMode="adjustPan|adjustResize"> </activity>
adjustResize : The activity's main window is always resized to make room for the soft keyboard on screen.
adjustPan : The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.
In your scenario you can make use of adjust pan
However it works based on the android versions. It may not work in particular versions. please be find and use.
Please have look at this answer you will come to know a lot.
Viewport height is the problem here.
There is some way to correct the problem with mediaqueries, or with javascript (modifying all of your dom element with the correct height).
But in my case, I had lots of dom elements, and really didn't want to change all of this with javascript.
My trick is :
- Change all of your vh with rem and divide your value by 4
- use this little javascript in all of your page :
$("html").css({"font-size": ($(window).height()/25)+"px"});
Here we go, in this example, font-size is 4% of window height (cause font-size has a minimum value on mobile app), so :
1rem=4% of widow height=4vh
0.25rem = 1vh etc...
In my case, I use a SASS function to divide with 4 all of my vh, so it was easier to change all css. (1h = rem(1) = 0.25rem)
Hope this will help someday.
This JS option delivers a UX similar to iOS:
let events = {
android: {
keyboard: {
threshold: 300, //px
transition: 300, //ms
visible: false,
last_el: null
}
}
}
onAndroidKeyboard() {
if(is_android) {
let threshold = events.android.keyboard.threshold;
let transition = events.android.keyboard.transition;
function onIn(e) {
let target = e.target;
if(target.nodeName.toLowerCase() !== 'input') {
return false
}
let visible = events.android.keyboard.visible;
let h = window.innerHeight;
try {
let bottom = target.getBoundingClientRect().bottom;
if(bottom) {
let diff = h - bottom;
if(diff < threshold) {
if(!visible) {
let animate_amount = threshold - diff;
events.android.keyboard.visible = true;
document.body.style.transform = 'translateY(0)';
document.body.style.webkitTransition = `all ${transition}ms`;
document.body.style.transition = `all ${transition}ms`;
events.android.keyboard.visible = true;
events.android.keyboard.last_el = target;
requestAnimationFrame(function () {
document.body.style.transform = `translateY(-${animate_amount}px)`;
});
}
}
}
} catch (e) {
console.error(e);
}
}
function onOut(e) {
let visible = events.android.keyboard.visible;
if(visible) {
document.body.style.transform = 'translateY(0)';
setTimeout(function () {
requestAnimationFrame(function () {
document.body.style.removeProperty('transform');
document.body.style.removeProperty('transition');
document.body.style.removeProperty('webkitTransition');
events.android.keyboard.visible = false;
events.android.keyboard.last_el = null;
});
}, transition)
}
}
document.addEventListener('focusin', onIn, false);
document.addEventListener('focusout', onOut, false);
}
}
I have an issue with the android softkeyboard overlapping the input fields when in focus. I have tried various solutions but to no avail. My application is built using phonegap I have tried to change the android:windowSoftInputMode to various solutions but everything doesn't work. these are the issues i ahve
1) The login screen input field does not focus into the center of the screen when in focus unless it is typed into. This is when the android:windowSoftInputMode="adjustPan".
2) If android:windowSoftInputMode="adjustResize" the input field does come into the center of the screen but only when typed into and this also breaks the layout of a bottom nav bar which is pushed up by the keyboard.
Does anyone have any advice on what I should do??
I had the same problem. Here is a workaround:
Install com.ionic.keyboard plugin
Set this in your config.xml
<preference name="fullscreen" value="true" />
Add this to the bottom of your page
<div id="kbs" class="keyboardspace"></div>
Give the surrounding element the id "frame"
Add this to your css
.keyboardspace {
width: 100%;
height: 0;
}
Now register these two event listeners (I'm using jquery here, but it should also be possible without)
var window = angular.element($window);
window.on('native.keyboardshow', function (e) {
$("#kbs").height(e.keyboardHeight);
var focus = $(document.activeElement);
var pos = focus.offset();
var bottom = pos.top + focus.height() + 10;
var maxpos = $($window).height() - e.keyboardHeight;
if (bottom > maxpos) {
$("#frame").scrollTop(bottom - maxpos);
}
});
window.on('native.keyboardhide', function () {
console.log("native.keyboardhide");
$("#kbs").height(0);
});
Note that the frame has to be scrollable for this to work.
You use this code in your Softkeyboard.java:
#override
public void onComputeInsets(Insets outInsets){
super.onComputeInsets(outInsets);
if(!isFullscreenMode()){
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
I'm trying to prevent scrolling of the body content when reaching the end of the scrollable content in a fixed div.
It was working really well in iOS, and still is, and well enough in Chrome on Android.
But when we did some testing a few days ago, suddenly it worked really bad in Chrome. It might be related to the release of Chrome 36 on the 14 of august.
When reaching the bottom of the fixed div, and I'll continue to "scroll" without stopping or lifting my finger, the body starts to scroll, even though it should be prevented by my script, and generated the following error message:
Ignored attempt to cancel a touchmove event with cancelable=false, for
example because scrolling is in progress and cannot be interrupted.
Is there anyway around this? Or some other trick I can use?
The following code is used:
var scrolling = false,
ts = null;
$('body').on('touchstart.scrollable', '.a', function(e) {
// Only execute the below code once at a time
if (!scrolling) {
scrolling = true;
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
scrolling = false;
}
ts = e.originalEvent.touches[0].clientY;
});
$('body').on('touchmove.scrollable', '.a', function(e) {
//If there is no scrollabe content we disable default event
var te = e.originalEvent.changedTouches[0].clientY,
direction = ts > te ? 'down' : 'up';
$container = $('.a');
$content = $('.b');
if ($content.height() <= $container.height()) {
e.preventDefault();
console.log('Default prevented');
} else if ($container.scrollTop() <= 1 && direction == 'up') {
e.preventDefault();
console.log('Default prevented');
} else if ($container.scrollTop() > 0 && ($container.scrollTop() + $container.height() >= $content.height() - 1) && direction == 'down') {
e.preventDefault();
console.log('Default prevented');
}
/* Keep from bubbling */
e.stopPropagation();
});
Please see the following example for complete source and to test:
Link to JSBin (They seems to expire after 24 hours) Please press File -> Clone if that has happend, and then view in fullscreen)
Thanks!
I had this issue recently on android. very frustrating, especially as the debug affects what happens.
In the end, I ended up putting a transparent div over the scrollable div and writing my own touch handlers on it that passed down the delta between the touchstart and touchmove event Y position to the scrollTop() function of the scrollable div (using jquery). This allowed me complete control of the scroll.
I thought I had it all worked out, then it stopped working again.
I added a wrapper around the menu with overflow-y: scroll and 10000px height.
Since the scroll bubbles I assumed it was gonna bubble to my wrapper and catch the scrolling there. But no, it goes straight to body and scrolls it. Even though it has static height to reflect the screen height and overflow: hidden!important.
It was however working when I had the wrapper selected in the DOM tree while debugging in Chrome. I no longer receive the error message when it's selected either.
It also works if you first scroll fast, let go, and let the scroll bubble to the body and continue scrolling until it stops by it self. Next time I scroll the prevent-method works and I don't receive the error message
I have no idea what the fudge is going on...
Calling preventDefault on touchmove while you are scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault() from touchstart and everything should be ok.
I've tried many different solutions and nothing is quite what I want. What I want is for the keyboard to show on top of the content (keeping the content the same size) while being able to scroll to input elements that are covered by the keyboard.
Every solution I've tried will either give me one or the other, but not both.
Solutions I've tried:
Solution here. Adding android:windowSoftInputMode="adjustPan" and android:configChanges="orientation|keyboardHidden" to the main activity in my AndroidManifest.xml.
The above solution using "adjustResize" instead of "adjustPan".
Solution here. Adding to my confix.xml.
Using adjustPan keeps my elements the same size, but disables scrolling. Using adjustResize resizes the entire page, making everything miniature. Keeping default settings, only the wrapper containing the input elements is resized, but scrolling is enabled.
I managed to find the exact same problem (unanswered) here. They were able to "fix" it by resizing their app to 150% and scroll to the covered input element, but like they said it's not ideal.
Any help is appreciated.
For most of the cases in config.xml change the full screen preference to false. that'll do the trick.
<preference name="fullscreen" value="false" />
I have the most efficient solution to scroll into input automatically and make it visible.
First you need to add the ionic keyboard plugin (works on any cordova project) because the eventlistener 'showkeyboard' does not work now.
cordova plugin add ionic-plugin-keyboard --save
Then on your event handler of 'keyboardshow' event add the following code:
window.addEventListener('native.keyboardshow', function(e){
setTimeout(function() {
document.activeElement.scrollIntoViewIfNeeded();
}, 100);
});
P.S: This is supported only on Android (Chrome) and Safari. :D
I had the same problem for android project output and in my situation the input elements were not moving upwards the keyboard . And after a-night-taking search (including those config changes and others) I found that in my angularjs cordova project
StatusBar.overlaysWebView(true);
StatusBar.hide();
lines which are in my controller causing that annoying problem . And I was using those lines for ios statusbar issues now I took those in an if condition and the problem is fixed.
if( device.platform=="iOS")
{
StatusBar.overlaysWebView(true);
StatusBar.hide();
}
You can detect focused textarea or input, then wait a while until keyboard is shown and finally scroll the page to reach focused input.
$("#textarea").focus(function(e) {
var container = $('#container'),
scrollTo = $('#textarea');
setTimeout((function() {
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});
}), 500);
});
When keyboard is hidden the textarea keeps focused, so if it's clicked again the keyboard will show and the container needs to scroll again to show the input
$("#textarea").click(function(e) {
e.stopPropagation();
var container = $('#container'), //container element to be scrolled, contains input
scrollTo = $('#textarea');
setTimeout((function() {
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});
}), 500);
});
Hope this helps, cheers!
I added an event listener for the keyboard event and scrolled to the input only if it was off screen.
For my case I only wanted to scroll when the keyboard was being shown for the first time, and only if the input item was offscreen.
document.addEventListener('showkeyboard', onKeyboardShow, false);
function onKeyboardShow(e) {
setTimeout(function() {
e.target.activeElement.scrollIntoViewIfNeeded()
}, 500) //needed timeout to wait for viewport to resize
}
To get the showkeyboard event to fire I needed to have the following in my AndroidManifest.xml
android:windowSoftInputMode="adjustResize"
I was also facing the same issue as it is a framework related issue. I have found work around-
constructor(
private platform: Platform,
private keyboard: Keyboard
) {
if(this.platform.is('android')){
this.keyboard.onKeyboardShow().subscribe((e) => {
var keyboardHeight = e.keyboardHeight;
keyboardHeight = keyboardHeight ? keyboardHeight : '337';
$('body').css('height', 'calc(100vh - ' + keyboardHeight + 'px)');
});
this.keyboard.onKeyboardHide().subscribe(e => {
$("body").css("height", "100vh");
});
}
}
I have used 337 which is keyboard height for default, mainly for that condition if keyboard height in not available.
library needed:
npm install jquery
npm install #types/jquery
ionic cordova plugin add cordova-plugin-ionic-keyboard
npm install #ionic-native/keyboard
imports
import { Platform } from '#ionic/angular';
import * as $ from "jquery";
import { Keyboard } from '#ionic-native/keyboard/ngx';
I came up with this solution. I have a full screen Vuejs application which the container has the height of the screen height and then absolute positioned to the bottom, left and right to fix the same sort of issue on IOS.
I then had the same issue on Android so came up with the following;
window.cordovaPluginIonicKeyboardShift = function()
{
/** This is my container (Vuejs instance) **/
const inst = document.querySelector('#app');
/** Get the height of the document **/
const height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
/** Where we will store the active input **/
let input;
/** The keyboard displaying is around 200 milliseconds **/
inst.style.transition = 'transform 0.2s';
/** Makes me feel better having this on to increase performance **/
inst.style.transform = 'translateZ(0)';
/**
* Set Input
* #param e
*/
let setInput = function(e) {
input = e.target;
};
/**
* On Keyboard Show
* #param event
*/
let onKeyboardShow = function(event) {
let offset = input.getBoundingClientRect();
if(offset.top + input.clientHeight > height - event.keyboardHeight) {
inst.style.transform = `translateZ(0) translateY(-${event.keyboardHeight}px)`;
}
};
/**
* OnKeyboard Hide
*/
let onKeyboardHide = function() {
inst.style.transform = `translateZ(0) translateY(0px)`;
};
/**
* Hide Keyboard
* #param e
*/
let hideKeyboard = function(e) {
if(e.target.tagName.toLowerCase() !== 'input' && e.target.tagName.toLowerCase() !== 'textarea') {
if(typeof input !== 'undefined') input.blur();
if(Keyboard.isVisible) Keyboard.hide();
}
};
/**
* Go through all inputs and textarea's on document and attach touchstart
* event. Using touchstart to define the input before focus which is what will trigger
* the keyboard.
*/
inst.querySelectorAll('input, textarea').forEach(function(elm) {
elm.removeEventListener('touchstart', setInput, false);
elm.addEventListener('touchstart', setInput, false);
});
/**
* Need to get the height to shift the document up by x amount
*/
window.removeEventListener('keyboardWillShow', onKeyboardShow, false);
window.addEventListener('keyboardWillShow', onKeyboardShow, false);
/**
* Shift it back down on keyboard hiding
*/
window.removeEventListener('keyboardWillHide', onKeyboardHide, false);
window.addEventListener('keyboardWillHide', onKeyboardHide, false);
/**
* Some browsers/phone models act odd when touching off the input
* so this is in to cover all bases
*/
document.removeEventListener('touchstart', hideKeyboard, false);
document.addEventListener('touchstart', hideKeyboard, false);
};
It also turns out even installing the plugin has affected the normal use of the keyboard which is why the hide method is called as the keyboard doesn't go away without it.
Then on my Vuejs instances I have the following updated method;
updated: function () {
this.$nextTick(function () {
cordovaPluginIonicKeyboardShift();
})
},
You'll also need to add this plugin;
phonegap cordova plugin add cordova-plugin-ionic-keyboard
Doing the above I have a successfully working fullscreen app with a working keyboard.
If you find yourself testing on Xcode Simulator and the keyboard is not showing, go to Simulator -> Device -> Erase all content and settings and re-install the app. No idea why this occurs but this will save you a lot of head aches.
Hope this helps someone
I figured out the problem. I have a media query in my CSS where the size of certain elements change for smaller screen sizes. Editing that query fixed my problem.
I am using the Cordova plugin 'ionic-plugin-keyboard' and listen to the 'native.keyboardshow' and 'native.keyboardhide' events to resize the HTML container element of my form:
window.addEventListener('native.keyboardshow', function (e) {
container.style.bottom = e.keyboardHeight + "px";
});
window.addEventListener('native.keyboardhide', function () {
container.style.bottom = null;
});
This results in the proper input fields to scroll into view (also when tabbing back and forward between the fields.
If you have made correctly the project as Cordova documentation says, It won't happen.
May be are you using a scroll library like iScroll?
I have been working on a project using PhoneGap and jQuery Mobile. My setup uses multiple pages inside a single html file.
I am facing a problem and I haven't found anything similar anywhere:
When I revisit a page, which means I visited it, then navigated to another page, and now returned to the first page, there is some padding between the header and the content, and also between the footer and the content of the page.
As screenshots show below:
http://i.imgur.com/neBwZYx.png
Below you can see the padding added, red background, when returned to the page above afterwards (this happens with every page)
http://i.imgur.com/u1whW9b.png
The code is very large to post here so if anyone has a suggestion please tell me how to fix this or where to look for the problem.
It should be noted that the problem exists only if the app runs on Android tablets, and not when viewed through the browser on my laptop.
Thank you
You can force correct content height with this function:
function getRealContentHeight() {
var header = $.mobile.activePage.find("div[data-role='header']:visible");
var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
var viewport_height = $(window).height();
var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
content_height -= (content.outerHeight() - content.height());
}
return content_height;
}
It must be activated during the pageshow event because only at that point page height is correct:
$(document).on('pageshow', '#index', function(){
$.mobile.activePage.find('.ui-content').height(getRealContentHeight());
});
Working example: http://jsfiddle.net/Gajotres/nVs9J/
If you want to find out more about this function read my other article: https://stackoverflow.com/a/14550417/1848600