Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Detect if a browser has a mouse or not
var md = new MouseDetector();
md.on('hasMouse', function() {
console.log("there's a mouse!");
});
md.on('noMouse', function() {
console.log("no mouse :(");
});
class MouseDetector
constructor: () ->
@events = {
hasMouse: []
noMouse: []
}
mousemoves = 0
mouseFirstMoved = null
mouseMovesThreshold = 5
mouseMovesTimeout = 1000
document.addEventListener "mousemove", =>
mousemoves++
mouseFirstMoved ||= +new Date()
if mousemoves > mouseMovesThreshold
if (mouseFirstMoved - +new Date()) < mouseMovesTimeout
@fire('hasMouse')
else
@fire('hasMouse')
document.removeEventListener "mousemove", arguments.callee
on: (name, cb) ->
@events[name]?.push cb
fire: (name) ->
for e in @events[name]
e()
var MouseDetector = (function() {
function MouseDetector() {
var mouseFirstMoved, mouseMovesThreshold, mouseMovesTimeout, mousemoves;
this.events = {
hasMouse: [],
noMouse: []
};
mousemoves = 0;
mouseFirstMoved = null;
mouseMovesThreshold = 5;
mouseMovesTimeout = 1000;
document.addEventListener("mousemove", (function(_this) {
return function() {
mousemoves++;
mouseFirstMoved || (mouseFirstMoved = +new Date());
if (mousemoves > mouseMovesThreshold) {
if ((mouseFirstMoved - +new Date()) < mouseMovesTimeout) {
_this.fire('hasMouse');
} else {
_this.fire('hasMouse');
}
return document.removeEventListener("mousemove", arguments.callee);
}
};
})(this));
}
MouseDetector.prototype.on = function(name, cb) {
var _ref;
return (_ref = this.events[name]) != null ? _ref.push(cb) : void 0;
};
MouseDetector.prototype.fire = function(name) {
var e, _i, _len, _ref, _results;
_ref = this.events[name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(e());
}
return _results;
};
return MouseDetector;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.