What is it ?
An ultra light ES6 singleton class to detect the pointer, listen to pointer type changes and add a specific class to all the HTMLElement you want when mouse is used.
850 bytes minified, 422 gzipped...
Demo
Current pointer detected | : | MOUSE |
Pointer Events Interface | : | POINTER |
Installation
npm
npm i -D amstramgram-pointer-detector
And then in your javascript :
import pointerDetector from 'Amstramgram-Pointer-Detector'
Manually
Just download the source and use it in your project.
import pointerDetector from './src_folder/amstramgramPointerDetector'
Usage
import pointerDetector from 'Amstramgram-Pointer-Detector'
//Add amst__mouse class to the body when mouse is used, remove it otherwise
pointerDetector.class('amst__mouse')
//Output "mouse", "touch" or "pointer" depending of the browser
console.log(pointerDetector.interface)
pointerDetector.on( _ => {
console.log('Pointer is now ' + pointerDetector.type)
})
API
type
/**
* @getter type
* @returns {string} "mouse", "pen" or "touch"
*/
console.log(pointerDetector.type)
interface
/**
* @getter interface
* @returns {string} "mouse", "pointer" or "touch"
*/
const p_interface = pointerDetector.interface
console.log(p_interface)
//Normalize pointer events
const
pointerenter = (p_interface == 'touch') ? 'none' : p_interface + 'enter',
pointerleave = (p_interface == 'touch') ? 'none' : p_interface + 'leave',
pointerup = (p_interface == 'touch') ? 'touchend' : p_interface + 'up',
pointerdown = (p_interface == 'touch') ? 'touchstart' : p_interface + 'down',
pointermove = p_interface + 'move'
document.body.addEventListener(pointerup, e => console.log(e, pointerup))
class
/**
* @param {String} mouseClass
* @param {HTMLElement} [el = document.body ]
* @description add the mouseClass class to the HTMLElement el when mouse is detected
*/
pointerDetector.class('amst__mouse')
pointerDetector.class('amst__mouse', document.querySelector('.myTestDiv'))
on
/**
* @param {function} : function to be called when pointerType changes
*/
pointerDetector.on(callback)
off
/**
* @param {function} : remove the given function from the on callbacks
*/
pointerDetector.off(callback)