Created
January 13, 2011 14:24
-
-
Save remy/777927 to your computer and use it in GitHub Desktop.
Simple tracking mouse object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Track(context) { | |
function addEvent(type, fn) { | |
// context is scoped in Track object | |
context.addEventListener(type, fn, false); | |
return addEvent; | |
} | |
function getXY(event) { | |
return { | |
x: (event.pageX || event.touches[0].pageX) - document.body.scrollLeft, | |
y: (event.pageY || event.touches[0].pageY) - document.body.scrollTop, | |
} | |
} | |
function down(event) { | |
track.down = true; | |
var coords = getXY(event); | |
track.downX = coords.x; | |
track.downY = coords.y; | |
track.downTime = +new Date; | |
} | |
function up(event) { | |
track.down = false; | |
track.delta = +new Date - track.downTime; | |
} | |
function move(event) { | |
var coords = getXY(event); | |
track.x = coords.x; | |
track.y = coords.y; | |
} | |
var track = this; | |
// http://twitter.com/LeaVerou/status/16613276313980928 | |
context || (context = document); | |
// hook up event listeners | |
addEvent('mousedown', down)('mouseup', up)('touchstart', down)('touchend', up)('mousemove', move)('touchmove', move)('keydown', function (event) { | |
track.key[event.which] = true; | |
})('keyup', function () { | |
track.key[event.which] = false; | |
}); | |
} | |
Track.prototype = { | |
key: {}, // note that key tracking isn't perfect yet - probably won't be :( | |
x: 0, | |
y: 0, | |
downTime: 0, | |
delta: 0, | |
downX: 0, | |
downY: 0, | |
down: false | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment