Dblclick event handler not responding for apple devices - javascript

Currently my application uses a FancyTree jquery plugin, the dblclick event is not working only for apple devices, when running in google chrome developer mode set on iphone7/8 it gives me the following error in console:
[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive.
However when switch off device toolbar, it is working fine.
same as for android and windows devices.
Also installing chrome on apple device will not work.
What can be the problem?
Thank you.
Installing doubletap.js gives no result.
Code from event handler in plugin
.on("click" + ns + " dblclick" + ns, function(event) {
if (opts.disabled) {
return true;
}
var ctx,
et = FT.getEventTarget(event),
node = et.node,
tree = self.tree,
prevPhase = tree.phase;
// self.tree.debug("event(" + event.type + "): node: ", node);
if (!node) {
return true; // Allow bubbling of other events
}
ctx = tree._makeHookContext(node, event);
// self.tree.debug("event(" + event.type + "): node: ", node);
try {
tree.phase = "userEvent";
switch (event.type) {
case "click":
ctx.targetType = et.type;
if (node.isPagingNode()) {
return (
tree._triggerNodeEvent(
"clickPaging",
ctx,
event
) === true
);
}
return tree._triggerNodeEvent(
"click",
ctx,
event
) === false
? false
: tree._callHook("nodeClick", ctx);
case "dblclick":
ctx.targetType = et.type;
return tree._triggerNodeEvent(
"dblclick",
ctx,
event
) === false
? false
: tree._callHook("nodeDblclick", ctx);
}
} finally {
tree.phase = prevPhase;
}
});
[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive

This is a bit of an obscure issue in Chrome. It is caused by a change back in Chrome 56 which is intended to improve scroll performance on mobile.
The workaround is to add a CSS rule like this:
#modal_valve
{
touch-action: none;
}
You may need to add it to other elements as well, depending on which elements gets dragged.

Related

Trigger click event of plus button on google plus

I cant trigger event onClick of plus button in Google plus
I have try with a method:
But it didn't work.
The code I tried
$(".mUbCce.fKz70d.GsLz7c.teCjMb.M9Bg4d").click()
I also noticed that when my mouse over the plus button, the mouse icon change to "hand-icon" but, I didn't find any CSS cursor for it.
Is there any magic from google ?
Thanks
Try this: Define a function fireEvent() like this:
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
And call
fireEvent($0,"mousedown")
fireEvent($0,"mouseup")
with $0 is the element you want to click

Vimeo iFrame Stealing Mouse Wheel Event on Firefox

I made this example here: http://jsbin.com/pokahec/edit?html,output
// creates a global "addWheelListener" method
// example: addWheelListener( elem, function( e ) { console.log( e.deltaY ); e.preventDefault(); } );
(function(window,document) {
var prefix = "", _addEventListener, onwheel, support;
// detect event model
if ( window.addEventListener ) {
_addEventListener = "addEventListener";
} else {
_addEventListener = "attachEvent";
prefix = "on";
}
// detect available wheel event
support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
"DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
window.addWheelListener = function( elem, callback, useCapture ) {
_addWheelListener( elem, support, callback, useCapture );
// handle MozMousePixelScroll in older Firefox
if( support == "DOMMouseScroll" ) {
_addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
}
};
function _addWheelListener( elem, eventName, callback, useCapture ) {
elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
!originalEvent && ( originalEvent = window.event );
// create a normalized event object
var event = {
// keep a ref to the original event object
originalEvent: originalEvent,
target: originalEvent.target || originalEvent.srcElement,
type: "wheel",
deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
deltaX: 0,
deltaZ: 0,
preventDefault: function() {
originalEvent.preventDefault ?
originalEvent.preventDefault() :
originalEvent.returnValue = false;
}
};
// calculate deltaY (and deltaX) according to the event
if ( support == "mousewheel" ) {
event.deltaY = - 1/40 * originalEvent.wheelDelta;
// Webkit also support wheelDeltaX
originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
} else {
event.deltaY = originalEvent.detail;
}
// it's time to fire the callback
return callback( event );
}, useCapture || false );
}
})(window,document);
You can test in Firefox that scroll event is fired, except when over vimeo iframe ( and I guess any iFrame )
Is there any solution to fire event on iframe ?
PS - I want to use this in a custom scrollbar
This is basically by design. Your code should be completely unaware of what the user does inside an IFRAME (especially one from a different origin like YouTube - this is a part of the web's security architecture, as mandated by the Same Origin Policy.)
Now, even in the cross-origin case browsers can choose to let scrolling affect the frame's ancestor if the frame itself doesn't scroll. This scrolling should happen without any events firing on the top document - see Chrome's behaviour if you scroll to the bottom of this IFRAME and keep scrolling:
http://jsfiddle.net/8cj0dofx/1/
HTML:
<iframe src="data:text/html,<body style='background:grey;height:550px'>Hello" seamless></iframe>
<div style="height:100px">Hello</div>
JS:
document.addEventListener('DOMMouseScroll', function(e){
document.getElementsByTagName('div')[0].firstChild.data += ' ' + e.type
});
document.addEventListener('mousewheel', function(e){
document.getElementsByTagName('div')[0].firstChild.data += ' ' + e.type
});
What you'll see is that when you have scrolled to the end of the IFRAME, the main document will scroll but no events will fire until the mouse is above the parent document.
It looks like it's a bug in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1084121
So there may not be a straightforward way to handle this. But since the action has an effect even if it's not being dispatched, there's a workaround that can be used. It may not work in every situation, but it should cover many cases.
Instead of detecting wheel event, you detect scroll, and use a switch detecting if the mouse is clicked or not. If the window scrolls and the mouse isn't clicked, then it's most likely from the mousewheel. Other cases will be if you trigger it from a script, in which case this can be handled easily also.
One case you won't handle is when the window cannot scroll anymore, then you won't get the event.
It would look like this:
var mouseDown = false;
function handle_wheel() {
if (!mouseDown) {
document.getElementById("debug-textarea").value = document.getElementById("debug-textarea").value + ' wheel';
} else {
document.getElementById("debug-textarea").value = document.getElementById("debug-textarea").value + ' scroll';
}
}
window.onscroll = handle_wheel;
window.onmousedown = function () {
mouseDown = true;
}
window.onmouseup = function () {
mouseDown = false;
}
http://jsfiddle.net/wu9y6yua/4/
I was facing the same problem but with a zoom on scroll feature.
Since it's not possible to capture the mousewheel event without hacks, I think the best option is to place a transparent div over the iframe and add the &autoplay=1 parameter
in the vimeo/youtube url on click.

Detect mouse on touch screen device

I use the following code to detect whether the device is a touch device or not:
var isTouchDevice = 'ontouchstart' in window || navigator.msMaxTouchPoints;
if(isTouchDevice)
{
$('body').addClass('yes-touch');
}
else
{
$('body').addClass('no-touch');
}
I use this to only show :hover states when it is NOT a touch device (as most touch devices interpret a tap as a hover).
.no-touch .element:hover {
color: red;
}
The problem is, one of our PCs in the office is an all-on-one touch screen PC, which means that when using a mouse the hover states don't occur.
Is there a way to work out whether a mouse is being used on a touch screen device? In other words, it should have the no-touch class applied when the mouse is being used and the yes-touch class applied when the touch screen is being used.
As of today, there is no foolproof ironclad way of doing it. The modernizr folks, pretty much the experts in feature detection, recently had this to say about it:
https://github.com/Modernizr/Modernizr/issues/869#issuecomment-57891034
The end result of all of this is that you cannot detect a mouse use in
a way that would conform to the level of reliability that Modernizr is
credited with. For our intents and purposes, it is a undetectable.
If you, future traveler, wish to attempt to detect a mouse user, then
the following is the best guide I can offer.
Don't. Seriously. Just because a user has a "mouse" doesn't mean that
they don't have multiple other forms of input. You should try really
hard to avoid making any kind of UI/UX decision that changes based
upon the idea of a mouse user being diametrically opposed to a
touchscreen user (or any other kind, for that matter). Make things
universal.
If you have to, and only care about IE 10 and 11, then IE's
PointerEvent would be worth checking out. Support is abysmal, outside
of those two (and presumably future IE versions).
You can attach a
listener for a 'hover' event on the body, and if it is true, then the
user probably has a mouse. The drawback with this approach include
touch events briefly firing hover events on tap/touch, so you could
get false positives.
sniff for mobile user agents. This is a bad idea,
and goes against the very core of Modernizr. Please don't do it.
So to me #1 pretty much sums it up. However, that answers your question but doesn't give you a solution. You mention "one of our PC's in the office..." Is this by chance an internal only application? I've occasionally run across situations where internal special use or one off pages may require some individual treatment for whatever reason (like one of our employees having a touch based AIO with a mouse attached). What I'll do then is append a ?hasmouse onto the end of the url and give the user that link to bookmark. Then inside javascript after your var isTouchDevice but before your if, insert this code to undo it:
if (location.search == '?hasmouse') {
isTouchDevice = false;
}
Again, thats sort of a no frills way for just internal use.
I have been using this for a while and it seems to work reliably. I wounder if it's worth it sometimes, but it does work.
The idea here is to capture actual touchdown events to trigger touch mode and use mousemove to trigger mouse mode. The problem is IE does not trigger touch events, but pointer events. The great thing about pointer events is you can check if it's mouse or touch!
The problem is all other browsers fire a fake mousemove just after a touch event. It's truly maddening!
You can see it work on this codepen
//First check if this is a touch device:
this.isTouch = 'ontouchstart' in window || (navigator.msMaxTouchPoints > 0);
// Some vars we'll need later
var lastTouch = 0
var lastCheck = 0
//Then set up our event listeners:
function initEvents() {
//handle touch/mouse devices detect mouse so that touch is toggled off
if (this.isTouch) {
$(document).on(" touchstart mousemove " + msPointerEvent('move'), function(e) {
e = e.originalEvent
//browser has pointer events
var pe = window.PointerEvent || window.MSPointerEvent
// handle ie pointer events (polyfill functions are at bottom of answer)
if (e.type == msPointerEvent('move')) {
var touchEvent = msPointerType(e) == 'touch'
if (touchEvent)
lastTouch = e.timeStamp;
if (!this.isTouch && touchEvent)
return setupTouch.call(this, true)
else if (this.isTouch && !touchEvent)
return setupTouch.call(this, false)
}
// Handle all other browser touch events
if (e.type == "touchstart") {
console.log('touchstart fired')
lastTouch = e.timeStamp;
if (!this.isTouch)
setupTouch.call(this, true);
}
// test mouse move and set up mouse mode if real
else if (!pe && e.type == "mousemove" && this.isTouch) {
if (realMouseDown.call(this, e)) {
setupTouch.call(this, false)
}
}
}.bind(this));
}
}
initEvents()
// Here is where we get clever. It turns out that the fake mousemove will fire in less than 500ms of the touch so we use that to detect fakes. Then of course do something special for IE:
function realMouseDown(e) {
var touchDif = e.timeStamp - lastTouch
var mouseDif = e.timeStamp - lastCheck
// false mouse event will get fired within 500ms of a touch (touchDif > 500)
// (required for all browsers false mouse after touch event)
var real = touchDif > 500
lastCheck = e.timeStamp;
console.log('real=', real, ' mDif ='+mouseDif, ' tDif ='+touchDif)
return real
}
// Now for some IE polyfill because they cant seem to make up their mind what to do.
// IE pointer event polyfill
function msPointerEvent(type) {
var n = ""
if (window.PointerEvent) // IE 11
n = 'pointer' + type
else if (window.MSPointerEvent) // IE 10
n = 'MSPointer' + type[0].toUpperCase() + type.substr(1);
return n
}
// IE pointer type polyfill
function msPointerType(e) {
var pt = ['zero', 'one', 'touch', 'pen', 'mouse']
return typeof e.pointerType == 'string' ? e.pointerType : pt[e.pointerType]
}
// And finally do what you need...
// make required changes for touch / mouse
var $output = $('#output')
function setupTouch(state) {
console.log('TouchMode=', state)
if (state)
this.isTouch = true
else
this.isTouch = false
$output.html('Touch mode changed to = '+state)
}
//First check if this is a touch device:
this.isTouch = 'ontouchstart' in window || (navigator.msMaxTouchPoints > 0);
// Some vars we'll need later
var lastTouch = 0
var lastCheck = 0
//Then set up our event listeners:
function initEvents() {
//handle touch/mouse devices detect mouse so that touch is toggled off
if (this.isTouch) {
$(document).on(" touchstart mousemove " + msPointerEvent('move'), function(e) {
e = e.originalEvent
//browser has pointer events
var pe = window.PointerEvent || window.MSPointerEvent
// handle ie pointer events (polyfill functions are at bottom of answer)
if (e.type == msPointerEvent('move')) {
var touchEvent = msPointerType(e) == 'touch'
if (touchEvent)
lastTouch = e.timeStamp;
if (!this.isTouch && touchEvent)
return setupTouch.call(this, true)
else if (this.isTouch && !touchEvent)
return setupTouch.call(this, false)
}
// Handle all other browser touch events
else if (e.type == "touchstart") {
console.log('touchstart fired')
lastTouch = e.timeStamp;
if (!this.isTouch)
setupTouch.call(this, true);
}
// test mouse move and set up mouse mode if real
else if (!pe && e.type == "mousemove" && this.isTouch) {
if (realMouseDown.call(this, e)) {
setupTouch.call(this, false)
}
}
}.bind(this));
}
}
initEvents()
// Here is where we get clever. It turns out that the fake mousemove will fire in less than 500ms of the touch so we use that to detect fakes:
function realMouseDown(e) {
var touchDif = e.timeStamp - lastTouch
var mouseDif = e.timeStamp - lastCheck
// false mouse event will get fired within 500ms of a touch (touchDif > 500)
// (required for all browsers false mouse after touch event)
var real = touchDif > 500
lastCheck = e.timeStamp;
console.log('real=', real, ' mDif =' + mouseDif, ' tDif =' + touchDif)
return real
}
// IE pointer event polyfill
function msPointerEvent(type) {
var n = ""
if (window.PointerEvent) // IE 11
n = 'pointer' + type
else if (window.MSPointerEvent) // IE 10
n = 'MSPointer' + type[0].toUpperCase() + type.substr(1);
return n
}
// IE pointer type polyfill
function msPointerType(e) {
var pt = ['zero', 'one', 'touch', 'pen', 'mouse']
return typeof e.pointerType == 'string' ? e.pointerType : pt[e.pointerType]
}
// make required changes for touch / mouse
var $output = $('#output')
function setupTouch(state) {
console.log('TouchMode=', state)
if (state) {
this.isTouch = true
$output.addClass('is-touch')
} else {
this.isTouch = false
$output.removeClass('is-touch')
}
$output.html('Touch mode changed to = ' + state)
}
body {
pointer-evetns: none;
}
#output.is-touch {
background-color: blue;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">
Touch or movethe mose on the result window to change the TouchMode state.
</div>
You can check for type of Pointer Event, that attached to Your object.
Please see example for hover below:
$('.element').on('pointerenter', function (e) {
if (e.pointerType == 'mouse') {
$(this).addClass('hover');
}
}).on('pointerleave', function (e) {
if (e.pointerType == 'mouse') {
$(this).removeClass('hover');
}
});
And use your css:
.element.hover {
color: red;
}

Check for Touch device with Javascript

I have 3 buttons with hover states which makes a little tooltip appear to describe the button. They work fine but on touchs screen they do not disappear after the user clicks on the button.
So I've tried a few js scripts for checking if a device is a touch device or not. They almost work but they also when I test on IE11 it also gets detected as a touch device. Chrome & Firefox do not get mistaken as a touch device.
Any sugestions?
Her is what I've tried
/*****************************
TOUCH DEVICES HOVER FIX START
****************************/
// http://stackoverflow.com/a/4819886/1814446
function isTouchDevice() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
};
// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/#poke-it
var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
hasTouch = true;
// Remove event listener once fired, otherwise it'll kill scrolling
// performance
window.removeEventListener('touchstart', setHasTouch);
}, false);
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
define(['Modernizr', 'prefixes', 'testStyles'], function( Modernizr, prefixes, testStyles ) {
// Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
Modernizr.addTest('touchevents', function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['#media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
});
});
if(bool===true) {
console.log('Touch Device'); //your logic for touch device
jQ( "#btn-1, #btn-2, #btn-3" ).click(function() {
jQ("#btn-1 .tooltip").css('opacity', '0');
jQ("#btn-2 .tooltip").css('opacity', '0');
jQ("#btn-3 .tooltip").css('opacity', '0');
});
}
else {
//your logic for non touch device
}
For IE10+ you can utilize "window.navigator.msMaxTouchPoints"
example code
function isIETouch ()
{
return window.navigator.msMaxTouchPoints == undefined ? false : window.navigator.msMaxTouchPoints;
}

Chrome (maybe Safari?) fires "blur" twice on input fields when browser loses focus

Here is an interesting jsfiddle.
In Firefox:
Run the fiddle
Click in text input
Click somewhere else. Should say "1 blurs".
Click in the text input again.
ALT-TAB to another window. Fiddle should now say "2 blurs".
In Chrome, at step 5, it says "3 blurs". Two separate "blur" events are fired when the whole browser loses focus. This is of interest because it means that it's not safe to assume, in a "blur" handler, that the element actually had focus just before the event was dispatched; that is, that the loss of focus — the transition from "being in focus" to "not being in focus" — is the reason for the event. When two "blur" events are generated, that condition is not satisfied during the handling of the second event, as the element is already not in focus.
So is this just a bug? Is there a way to tell that a "blur" event is bogus?
The reason it is firing twice is because of window.onblur. The window blurring triggers a blur event on all elements in that window as part of the way javascript's capturing/bubbling process. All you need to do is test the event target for being the window.
var blurCount = 0;
var isTargetWindow = false;
$(window).blur(function(e){
console.log(e.target);
isTargetWindow = true;
});
$(window).focus(function(){
isTargetWindow = false;
});
$('input').blur(function(e) {
if(!isTargetWindow){
$('div').text(++blurCount + ' blurs');
}
console.log(e.target);
});
​
http://jsfiddle.net/pDYsM/4/
This is confirmed Chrome bug. See the Chromium Issue Tracker
The workaround is in the accepted answer.
Skip 2nd blur:
var secondBlur = false;
this.onblur = function(){
if(secondBlur)return;
secondBlur = true;
//do whatever
}
this.onfocus = function(){
secondBlur = false;
//do whatever
}
This probably isn't what you want to hear, but the only way to do it seems to be to manually track whether the element is focused or not. For example (fiddle here):
var blurCount = 0;
document.getElementsByTagName('input')[0].onblur = function(e) {
if (!e) e = window.event;
console.log('blur', e);
if (!(e.target || e.srcElement)['data-focused']) return;
(e.target || e.srcElement)['data-focused'] = false;
document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
};
document.getElementsByTagName('input')[0].onfocus = function(e) {
if (!e) e = window.event;
console.log('focus', e);
(e.target || e.srcElement)['data-focused'] = true;
};
Interestingly, I couldn't get this to work in jQuery (fiddle here) ... I really don't use jQuery much, maybe I'm doing something wrong here?
var blurCount = 0;
$('input').blur(function(e) {
console.log('blur', e);
if (!(e.target || e.srcElement)['data-focused']) return;
(e.target || e.srcElement)['data-focused'] = false;
$('div').innerHTML = (++blurCount + ' blurs');
});
$('input').focus(function(e) {
console.log('focus', e);
(e.target || e.srcElement)['data-focused'] = true;
});
You could also try comparing the event's target with document.activeElement. This example will ignore the alt+tab blur events, and the blur events resulting from clicking on Chrome's... chrome. This could be useful depending on the situation. If the user alt+tabs back into Chrome, it's as if the box never lost focus (fiddle).
var blurCount = 0;
document.getElementsByTagName('input')[0].onblur = function(e) {
if (!e) e = window.event;
console.log('blur', e, document.activeElement, (e.target || e.srcElement));
if ((e.target || e.srcElement) == document.activeElement) return;
document.getElementsByTagName('div')[0].innerHTML = (++blurCount + ' blurs');
};​
​
I'm on Chrome Version 30.0.1599.101 m on Windows 7 and this issue appears to have been fixed.
I am experiencing the same and the above posts make sense as to why. In my case I just wanted to know if at least one blur event had occurred. As a result I found that just returning from my blur function solved my issue and prevented the subsequent event from firing.
function handleEditGroup(id) {
var groupLabelObject = $('#' + id);
var originalText = groupLabelObject.text();
groupLabelObject.attr('contenteditable', true)
.focus().blur(function () {
$(this).removeAttr('contenteditable');
$(this).text($(this).text().substr(0, 60));
if ($(this).text() != originalText) {
alert("Change Found");
return; //<--- Added this Return.
}
});
}
Looks like an oddity of angularjs gives a simpler solution when using ng-blur; the $event object is only defined if you pass it in:
ng-blur="onBlur($event)"
so (if you aren't using ng-blur on the window) you can check for:
$scope.onBlur = function( $event ) {
if (event != undefined) {
//this is the blur on the element
}
}

Categories

Resources