Skip to content

Instantly share code, notes, and snippets.

@arniebradfo
Last active May 27, 2018 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arniebradfo/1e470a22e9b37185d2a5479d5cb327b7 to your computer and use it in GitHub Desktop.
Save arniebradfo/1e470a22e9b37185d2a5479d5cb327b7 to your computer and use it in GitHub Desktop.
Device Mouse or Touch Input Detection
.input-mouse button:hover{
background-color: black;
color: white;
}
export class InputDetectionService {
public get isInputMouse(): boolean { return !this._isInputTouch };
public get isInputTouch(): boolean { return this._isInputTouch };
private _isInputTouch: boolean = false;
private _element: HTMLElement = document.body;
private _switchToTouchRef = this._switchToTouch.bind(this);
private _switchToMouseRef = this._switchToMouse.bind(this);
private _recordEventTimeStampRef = this._recordEventTimeStamp.bind(this);
private _touchEndTimeStamp: number;
constructor() {
this._switchToMouse(); // or...
// this._switchToTouch(); // if we expect a mobile device more often
}
private _switchToTouch() {
document.removeEventListener('touchstart', this._switchToTouchRef, true);
document.addEventListener('touchend', this._recordEventTimeStampRef, true);
document.addEventListener('mousemove', this._switchToMouseRef, true);
this._element.classList.remove('input-mouse');
this._element.classList.add('input-touch');
this._isInputTouch = true;
}
private _switchToMouse(event?: MouseEvent) {
// 'touchend' and 'mousemove' both fire at the end of a touch press on android
// event.timeStamp should equal this._touchEndTimeStamp exactly, but lets allow a margin of error
if (event && event.timeStamp - this._touchEndTimeStamp < 10)
return; // filter out the 'mousemove' that occur after presses on a touch device
document.addEventListener('touchstart', this._switchToTouchRef, true);
document.removeEventListener('touchend', this._recordEventTimeStampRef, true);
document.removeEventListener('mousemove', this._switchToMouseRef, true);
this._element.classList.add('input-mouse');
this._element.classList.remove('input-touch');
this._isInputTouch = false;
}
private _recordEventTimeStamp(event: TouchEvent) {
// record the 'touchend' time stamp to compare with 'mousemove' in_switchToMouse
this._touchEndTimeStamp = event.timeStamp
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment