In Android Browser link does not always execute onClick causing focus instead - android

I am trying to program a very standard JS behavior for a link using an HREF
onClick handler, and I am facing a strange problem caused by what I believe to be focus/touch mode behavior on Android.
Sometimes when I click on the link, instead of executing the action, it simply becomes selected/focused, with either just a focus rectangle or even also with a filled focus rectangle (selected as opposed to just focused?).
The pseudo-code right now is
go
I have tried doing something like:
go
But I still get the same pesky problem some of the time.

Try enabling Javascript on the webview.
In the activity that holds the webview, try this...
WebView wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
I was having he same problem, but figured out it was because I did not enabled Javascript.

Try getting rid of the href attribute and see if that helps. For example, this works when viewed with the WebView component:
<p><a onClick="whereami()">Update Location</a></p>

I wonder if it's related to the onclick -- am I correct to assume that every now and then clicking any link does not follow it? To me, this seems related to the way you touch the screen (or how this is interpreted), like maybe by clicking next to the link and dragging a bit, rather than clicking on the link?
(If my assumption is correct, then this might be faulty hardware: maybe you can try on another device? Or maybe it only happens on a particular side of the link if the screen is not aligned well, and then there might be some software offset one can change?)

Try inserting this "driver" into your page code, and let us know if it works . . . It seems to be working on my site which had the same problem:
//Mouse & Touch -> Consistent Click / Mouse Commands -> Useful driver
(function() {
var isTouch = false;
var simulated_flag = 'handler_simulated';
var touch_click_array = {};
const clickMoveThreshold = 20; //Pixels
function mouseHandler(event) {
if (isTouch) {
if (!event.hasOwnProperty(simulated_flag)) {
//Unreliable mouse commands - In my opinion
var fixed = new jQuery.Event(event);
fixed.preventDefault();
fixed.stopPropagation();
}
}
else {
//Mouse commands are consistent
//TODO: generate corresponding touches
}
}
function mouseFromTouch(type, touch) {
var event = document.createEvent("MouseEvent");
event.initMouseEvent(type, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY
, false, false, false, false, 0, null);
event[simulated_flag] = true;
touch.target.dispatchEvent(event);
};
function touchHandler(event) {
var touches = event.changedTouches
,first = touches[0]
,type = ""
;
if (!event.hasOwnProperty(simulated_flag)) {
isTouch = true;
//Simulate mouse commands
switch (event.type) {
case "touchstart":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch_click_array[touch.identifier] = { x: touch.screenX, y: touch.screenY };
}
mouseFromTouch("mousedown", first);
break;
case "touchmove":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
var id = touch.identifier;
var data = touch_click_array[id];
if (data !== undefined) {
if (Math.abs(data.x - touch.screenX) + Math.abs(data.y - touch.screenY) > clickMoveThreshold) {
delete touch_click_array[id];
}
}
}
mouseFromTouch("mousemove", first);
break;
case "touchcancel":
//Not sure what should happen here . . .
break;
case "touchend":
mouseFromTouch("mouseup", first);
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
if (touch_click_array.hasOwnProperty(touch.identifier)) {
mouseFromTouch("click", touch);
delete touch_click_array[touch.identifier];
}
}
break;
}
}
}
document.addEventListener("mousedown", mouseHandler, true);
document.addEventListener("mousemove", mouseHandler, true);
document.addEventListener("mouseup", mouseHandler, true);
document.addEventListener("click", mouseHandler, true);
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
})();
Now it isn't a 100% complete script - multi-touch would probably be a little wonky, and if you built an interface depending on touch commands, it doesn't generate those in this version. But, it fixed my link-clicking problem.
Erm - ps - it's using jQuery. If you need a non-jQuery version, you can probably just remove the new jQuery.Event from the mouseHandler() function (in other words, use the original event: var fixed = event;), and I believe most browsers would be ok. I am not exactly a js compatibility expert though.
PPS - Tested with Android 1.6
PPPS - Had to modify script to allow a threshold - actual devices were having some problems with a move event being fired during the press. Probably not ideal; if anyone wants to chime in on a better way for doing that, I'd be interested in hearing...

Recently I came across exactly the same problem. I was using the onclick on a button. Sometimes it did not execute the javascript at all. The thing that worked for me was that enable the javascript before loading a url in the webview
// Enable javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// To bind javascript code to android
mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
mWebView.loadUrl(url);

Related

How to have separate pages for iOS Web App and just browser? [duplicate]

If a user visits my websites example, from Safari Mobile how could I place there a blank page that says "Add To Homescreen."? Once added it would show different content.
You'll want to check two things. First, is it running on an iOS device? Second, is window.navigator.standalone == true?
window.navigator.standalone is primarily used by Webkit browsers to indicate the app is in fullscreen (or standalone) mode. Plenty of devices (like phones running Android), support this property, but don't have the option to 'Add to Homescreen' like iOS devices do, so you need to check both.
Demo:
Javascript:
function isIOS() {
var userAgent = window.navigator.userAgent.toLowerCase();
return /iphone|ipad|ipod/.test( userAgent );
};
function isStandalone() {
return ( isIOS() && window.navigator.standalone );
};
window.onload = function () {
if( isStandalone() || !isIOS() ) { //either ios+standalone or not ios
//start app
} else {
//display add to homescreen page
};
};
Check window.navigator.standalone.
Slight slight different code, based on #ThinkingStiff solution, and this other question on this Post, to support IOS7 detection to provide CSS interface to add more padding-top in case of transparent app title.
isIOS7 = function() {
return navigator.userAgent.match(/(iPad|iPhone|iPod touch);.*CPU.*OS 7_\d/i);
};
isStandaloneAndIOS7 = function() {
return isIOS7() && window.navigator.standalone;
};
if (isStandaloneAndIOS7()) {
body = document.getElementsByTagName("body")[0];
body.className = body.className + " standalone";
}

jQuery Dropdown Menu with Android

I wrote this script for a navigation menu on the phone. If an item has drop downs, it prevents the link, then displays the drpdown.
$(document).ready(function() {
var bodyWidth = window.screen.availWidth;
if(bodyWidth <= 600) {
$('ul.dropdowns li > a').click(function(event) {
var parent = $(this).closest('li');
var nester = $(this).closest('li').closest('ul').closest('li');
var type = parent.attr("class");
if(parent.hasClass('dropdown') || parent.hasClass('flyout')) {
event.preventDefault();
$(parent).siblings().attr("id", "");
var isActive = (parent.attr("id") == "active" ? true : false);
(isActive ? $(parent).attr("id", "") : $(parent).attr("id", "active"));
}
});
};
});
This works fine with the iPhone, but on Android it gets screwed. I'm at a total loss, any ideas?
By, "gets screwed" I mean nothing happens on Android when you try to click a link.
I found the problem. I was using a CSS transition that for some reason Android wasn't keeping up with.

keyup not working on Chrome on Android

I am using bootstrap typeahead.
It depends on this jQuery code to work:
el.on('keyup', doSomething() )
On Chrome on Windows it works fine. On Chrome on Android it doesn't. The keyup event is never fired. The element to which it is bound definitely has the focus.
This appears to be a recent development.
Chrome 28.0.1500.64
Android 4.1.2 SGP321 Build/10.1.1.A.1.307
Thanks
--Justin Wyllie
I came across this same problem earlier today. How can android chrome not support these key events! I assume you've found a workaround by now, but here's a fix that I came up with for now.
function newKeyUpDown(originalFunction, eventType) {
return function() {
if ("ontouchstart" in document.documentElement) { // if it's a touch device, or test here specifically for android chrome
var $element = $(this), $input = null;
if (/input/i.test($element.prop('tagName')))
$input = $element;
else if ($('input', $element).size() > 0)
$input = $($('input', $element).get(0));
if ($input) {
var currentVal = $input.val(), checkInterval = null;
$input.focus(function(e) {
clearInterval(checkInterval);
checkInterval = setInterval(function() {
if ($input.val() != currentVal) {
var event = jQuery.Event(eventType);
currentVal = $input.val();
event.which = event.keyCode = (currentVal && currentVal.length > 0) ? currentVal.charCodeAt(currentVal.length - 1) : '';
$input.trigger(event);
}
}, 30);
});
$input.blur(function() {
clearInterval(checkInterval);
});
}
}
return originalFunction.apply(this, arguments);
}
}
$.fn.keyup = newKeyUpDown($.fn.keyup, 'keyup');
$.fn.keydown = newKeyUpDown($.fn.keydown, 'keydown');
Sorry to say this but keyup/keydown events do not work for chrome browser in android.
There are other people who have reported this issue(Here and Here) from last 1 year and its not fixed yet. so it's better for developers to avoid using these events till it gets fixed.

Android 4.1 change - transition and webkittransition defiend, how to properly determine name of transition end event?

I have noticed that with the update from android 4.0 to 4.1, there is a change as to css transition prefix in the stock browser & webView
Basically, both "transition" and "webkitTrantion" are defiend.
Modernizr.prefixed("transition") returns webkitTrantion on android 4.0
Modernizr.prefixed("transition") returns trantion on android 4.1
However, as to transition end event name, "transitionend" event is not defined / does not work. you still need to use the webkit specific "webkitTransitionEnd" event name
QUESTION: I cannot find any documentation on this change, and thus are not certain how to proceed... can anyone shed some light on this? any suggestions or links to docs woudl be greatly appreciated!
TO REPRODUCE:
function whichTransitionEvent(){
var t;
var el = document.createElement('fakeelement');
var transitions = {
'OTransition':'oTransitionEnd',
'MSTransition':'msTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd',
'transition':'transitionEnd'
}
for(t in transitions){
if( el.style[t] !== undefined ){
alert (transitions[t]);
}
}
}
The code above, will result in just one popup showing up on android 4.0, and 2 popups for android 4.1 since on 4.1, both "transition" and "webkitTransition" as valid
I had a similar problem where Chrome on desktop and Android on Samsung devices would report another event name than what they actually used. The only way I can think of that would find what they are actually using is by triggering an event, set up several different event listeners, and see which one was triggered. The code below (from this gist) essentially does this and sets Modernizr.transitionEnd to be that eventname.
var $M = window.Modernizr
var _ = window._ // underscore.js
// Defines prefixed versions of the
// transitionEnd event handler
transitionFinishedEvents = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'msTransitionEnd',
'transition' : 'transitionEnd'
};
// Feature detect actual transitionEnd keyword by triggering an event
window.setTimeout(function () {
var div = document.createElement('div');
div.id = "my-transition-test";
div.style.position = 'absolute';
div.style.zIndex = -10;
div.style.bottom = '-1000px';
div.style.height = '100px';
div.style.width = '100px';
div.style.background = 'yellow';
div.style.display = 'hidden';
window.document.body.appendChild(div);
$('#my-transition-test').one(_.values(transitionFinishedEvents).join(" "), function (e) {
if ($M.transitionFinishedEvent !== e.type) {
window.console.warn("Changing misconfigured Modernizr.transitionFinishedEvent to " + e.type + ". (Was " + $M.transitionFinishedEvent + ")");
$M.transitionFinishedEvent = e.type;
}
window.document.body.removeChild(div);
});
window.setTimeout(function () {
div.style[$M.prefixed('transition')] = '0.1s';
div.style[$M.prefixed('transform')] = 'translate3d( 100px,0,0)';
}, 25);
}, 25);
Afterwards you can easily set up an event listener for transitionEnd that will work on all platforms (that has CSS3 transitions):
$("#fooBar").on($M.transitionEnd, function() {
// do something clever
}
The code has dependencies on underscore.js and jQuery, but can easily be turned into vanilla js.
Relevant links for people affected by this:
[Modernizr]Unprefixed version of 'transition' and 'transform' incorrectly returned for Android 4.1.1 (Samsung Note II)
[Leaflet] Freeze on Android 4.1.1 + Samsung Galaxy Note II

Is it possible to scroll divs in Chrome for Android?

Here is a chunk of text inside a scrollable div.
I can scroll it with two fingers in Chrome for Mac. I can scroll it with one finger on my iPad. However, I can't find any way to scroll it in Chrome for Android.
Perhaps there's a work-around using the touch API?
Another quick fix for Chrome for Android (http://chris-barr.com/index.php/entry/scrolling_a_overflowauto_element_on_a_touch_screen_device/)
First create a function to check whether the it is a touch device...
function isTouchDevice(){
try {
document.createEvent("TouchEvent");
return true;
} catch(e) {
return false;
}
}
then function to make div scrollable
function touchScroll(id){
if( isTouchDevice() ){ //if touch events exist...
var el = document.getElementById(id);
var scrollStartPos = 0;
document.getElementById(id).addEventListener("touchstart", function(event){
scrollStartPos = this.scrollTop + event.touches[0].pageY;
event.preventDefault();
}, false);
document.getElementById(id).addEventListener("touchmove", function(event){
this.scrollTop = scrollStartPos - event.touches[0].pageY;
event.preventDefault();
},false);
}
}
... call the function passing the element id
touchScroll("divIdName");
While browsing through the bug reports on this issue, I found this JavaScript library that solves the problem using touch events. Also it is reportedly fixed in Honeycomb, so hopefully the fix will hit people as soon as they push builds of Ice Cream Sandwich.
All android versions before 3.0 are bugged with overflow:scroll or auto (bug info).
For thoses using jQuery here is a quick fix :
function touchScroll(selector){
var scrollStartPos = 0;
$(selector).live('touchstart', function(event) {
scrollStartPos = this.scrollTop + event.originalEvent.touches[0].pageY;
});
$(selector).live('touchmove', function(event) {
this.scrollTop = scrollStartPos - event.originalEvent.touches[0].pageY;
});
}
and then if using modernizr :
if (Modernizr.touch) {
touchScroll($('.myScrollableContent'))
}
but it's not ideal because all touch-able devices will have this.
If you use Phonegap you can do (somewhere after phonegap inited):
if (window.device && device.platform=="Android" && parseInt(device.version) < 3){
touchScroll($('.myScrollableContent'))
}

Categories

Resources