i want to get rid off the error "referenceError: can't find variable TouchEvent" on safari browser. My code is as below,
function copy_mouse_event(event) {
const event_init = {
// EventInit
bubbles: event.bubbles,
eventPhase: event.eventPhase,
// UIEventInit
detail: event.detail,
view: event.view,
// EventModifierInit
altKey: event.altKey,
ctrlKey: event.ctrlKey
};
// initialise MouseEvent data which is shared by wheel, mouse and pointer events
let mouse_event_init = {};
if (event instanceof MouseEvent) {
mouse_event_init = {
...event_init,
button: event.button,
buttons: event.buttons,
clientX: event.clientX,
clientY: event.clientY,
relatedTarget: event.relatedTarget,
screenX: event.screenX,
screenY: event.screenY
};
if (event instanceof WheelEvent) {
const wheel_event_init = {
...mouse_event_init,
deltaMode: event.deltaMode,
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaZ: event.deltaZ,
wheelDelta: event.wheelDelta,
wheelDeltaX: event.wheelDeltaX,
wheelDeltaY: event.wheelDeltaY
};
return new WheelEvent(event.type, wheel_event_init);
}
}
// try the modern pointer event first, then mouse and touch events
if (event instanceof PointerEvent) {
const pointer_event_init = {
...mouse_event_init,
pointerId: event.pointerId,
width: event.width,
height: event.height,
};
return new PointerEvent(event.type, pointer_event_init);
} else if (event instanceof MouseEvent) {
return new MouseEvent(event.type, mouse_event_init);
} else if (event instanceof TouchEvent) {
//error occurs here only on safari
const touch_event_init = {
...event_init,
changedTouches: event.changedTouches,
targetTouches: event.targetTouches,
touches: event.touches
};
return new TouchEvent(event.type, touch_event_init);
}
}
Since safari browser doesnt support touch event, i was thinking to fix by checking if touchevent exists. How can i check if touchevent exists or not. could someone help me with this. thanks.
To check for the existence of TouchEvent
, you can do:
if ('TouchEvent' in window) {
...
}
Just checking for TouchEvent
, as in if (TouchEvent ...)
won't work, as if it is not defined, you'll get a runtime error. The valid way to do this would be:
if (window.TouchEvent) {
...
}
EDITED: If you want to use typeof
, you can do it like this:
if (typeof TouchEvent !== 'undefined') {
...
}
Use the approach you prefer, as both work.
Hope this helps.
You can simply do it by having this check forinteraction media features :
if(window.matchMedia("(pointer: coarse)").matches) {
// touchscreen
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.