Skip to content

Instantly share code, notes, and snippets.

@enwin
Created March 7, 2023 10:51
Show Gist options
  • Save enwin/6bdd6dac614d80ddb9bfa9c8da0346d6 to your computer and use it in GitHub Desktop.
Save enwin/6bdd6dac614d80ddb9bfa9c8da0346d6 to your computer and use it in GitHub Desktop.
Detect current input used to interact with the website
@mixin interact() {
-webkit-tap-highlight-color: rgba(black, 0);
&:focus {
outline: none;
}
[data-input='mouse'] &:hover,
[data-input='keyboard'] &:focus,
[data-input='touch'] &:active {
@content;
}
}
export class InputType {
constructor() {
this.properties = {
inputType: document.documentElement.getAttribute('data-input') || '',
};
// listen to pointer to detect current use of the page
if (window.PointerEvent) {
window.addEventListener(
'pointerdown',
(event) => {
this.detectInputType(event);
},
{
passive: true,
}
);
window.addEventListener(
'pointermove',
(event) => {
this.detectInputType(event);
},
{
passive: true,
}
);
// fallback for old browsers
} else {
window.addEventListener(
'mousemove',
(event) => {
this.detectInputTypeFallback(event);
},
{
passive: true,
}
);
window.addEventListener(
'touchstart',
(event) => {
this.detectInputTypeFallback(event);
},
{
passive: true,
}
);
}
// listen to keyboard to detect current use of the page
window.addEventListener(
'keydown',
() => {
this.handleKeys();
},
{
passive: true,
}
);
}
detectInputType(event) {
this.inputType = event.pointerType;
}
detectInputTypeFallback(event) {
this.inputType = event.type === 'mousemove' ? 'mouse' : 'touch';
}
handleKeys() {
this.inputType = 'keyboard';
}
set inputType(value) {
if (value === this.properties.inputType) {
return;
}
this.properties.inputType = value;
// set the custom data-input attribute so CSS can use it
document.documentElement.setAttribute('data-input', value);
}
get inputType() {
return this.properties.inputType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment