I have a div
that can be horizontally scrolled back and forth by clicking and dragging. What I need now is to get the cumulative change in the mouse's x-axis position while dragging around, even before onmouseup
.
The heart of my problem right now is that because onmousemove
fires every time the mouse moves 1px, the delta intervals are too tight for this relative change to be of any significance to these other functions that would use var deltaScroll
.
I think what I need is a way to fetter this stream of data with a loop that accumulates incoming deltaScroll
values into a single variable which oscillates with their rising and falling. I could be wrong though - if there's another way to do this, I'd love to hear it.
Currently using something more or less like the following:
var mouseDelta;
var prevDelta;
var deltaScroll;
$("#my-scrolling-div").mousedown(function (event) {
//confirm mouse button is down
$(this).data('down', true)
//get mouse's x-axis position onmousedown
.data('x', event.clientX)
//get the div's scrollLeft position onmousedown
.data('scrollLeft', this.scrollLeft);
//just so browser won't highlight the div's content when dragging around
return false;
}).mouseup(function (event) {
//confirm mouse button is released
$(this).data('down', false);
}).mousemove(function (event) {
//whenever mouse moves, if mouse button is down... (here there be dragons.)
if ($(this).data('down') == true) {
//scroll the div by the mouse's delta X since mousedown. fine.
this.scrollLeft = $(this).data('scrollLeft') + $(this).data('x') - event.clientX;
//set mouseDelta to equal the mouse's current delta X since onmousedown
mouseDelta = $(this).data('x') - event.clientX;
//get the difference between current delta and the delta logged from the last onmousemove
deltaScroll = mouseDelta - prevDelta;
//pass this relative change (delta of delta, change in change) through an external function, more than one in actuality
someFunction(deltaScroll);
//log mouseDelta at the end of each mousemove so we have something to set deltaScroll by on the next pass
prevDelta = mouseDelta;
}
});
This seems like it should be pretty straight forward, but I'm strapped for ideas. Thanks in advance.
EDIT: This feels like an unreasonably hacky solution, but now I'm appending these delta values to a hidden HTML element as a string, so I end up with getting what I want with something like this:
if (isNaN(deltaScroll) == false){
var strAdd = " + " + deltaScroll;
$('#hidden-div').append(strAdd);
//ends up accumulating into something like 0 + 3 + 151 + -447 + -45 + 168 + 61 + 21 + 19...
var sum = eval($('#hidden-div').html());
someFunction(sum);
}
There has to be a cleaner way... Thoughts?