MouseMoveDelta
by sinky
HTML
<div id="area"></div>
CSS
#area {
width: 300px;
height: 300px;
margin: 200px;
background: #123456;
}
JavaScript
/*
MouseMoveDelta
==============
In my use case I needed to know how fast a cursor is moving on an object and trigger a specific action if it is slow enough.
So this plugin triggers an event containing the movement of the cursor since its last occurrence in a given time interval.
@author: Nico Knoll <https://github.com/NicoKnoll/>
*/
;
(function($, window, document, undefined) {
var Plugin = function(target, options) {
this.target = $(target);
this.options = options;
this.interval = null;
this.prevPosition = {
x: 0,
y: 0
};
this.currentPosition = {
x: 0,
y: 0
};
};
Plugin.prototype = {
defaults: {
intervalOffset: 100,
decimalPlaces: 2
},
init: function() {
var self = this;
self.config = $.extend({}, self.defaults, self.options);
self.first = true;
self.target.mouseenter(function(e) {
self.interval = setInterval(function() {
var deltaObject = {};
deltaObject.x = self.currentPosition.x - self.prevPosition.x;
deltaObject.y = self.currentPosition.y - self.prevPosition.y;
deltaObject.delta = roundWithPlaces((Math.sqrt(Math.pow(deltaObject.x, 2) + Math.pow(deltaObject.y, 2))), self.config.decimalPlaces);
self.prevPosition.x = self.currentPosition.x;
self.prevPosition.y = self.currentPosition.y;
if (!self.first) {
self.target.trigger('mousemovedelta', deltaObject);
}
self.first = false;
}, self.config.intervalOffset);
});
self.target.mousemove(function(e) {
self.currentPosition.x = e.pageX;
self.currentPosition.y = e.pageY;
});
self.target.mouseleave(function(e) {
clearInterval(self.interval);
self.interval = null;
self.first = true;
});
return self;
},
};
var roundWithPlaces = function(value, places) {
var multiplier = Math.pow(10, places);
...