Redirect (touch) scroll event from one element to another


I have a case in which, I need to scroll a <div> even when the mouse pointer is not on it. Instead, no matter where in my document’s <body> the mouse wheel is scrolled, the <div> should get scrolled. Luckily it was easy to implement for a mouse based device:

var target = $('.scroll').get(0);
$('body').on('wheel', function (e)
		var o = e.originalEvent;
		target.scrollTop += o.deltaY;

Here’s an example on JSFiddle:

I’d like to emulate a similar behaviour on a touch based device. It has been brought to my notice that toucmove event shall be used instead of the wheel event. However, the touchmove event doesn’t give deltaY positions like the wheel event.

Can someone please help me convert this into a proper working code for touch devices. I have been trying a lot of codes and I had got kind of successful (it wasn’t scrolling beyond 10 pixels) with one, but, that was yesterday and I deleted that code to try a new one. If I recollect that code, I’ll update this thread, but, till then, some other help will be greatly appreciated.

EDIT: My code was something on these lines:

var lastY = 0;
$('body').bind('touchmove', function (e)
		var currentY = e.originalEvent.touches[0].clientY;
		var deltaY2 = currentY-lastY;
		('.scroll').scrollTop = deltaY2;
		lastY = currentY;

Hi @hrishi5200, there are a couple of issues with that code: you forgot the $ so you’re effectively setting a scrollTop on the string ".scroll"; furthermore, in jQuery that would have to be a function call rather than an assignment; and you should add the delta to the scroll top, not set it to the delta; and finally, you have to clear the last touch on touch end so it doesn’t get set back when the next move occurs. So together it should look something like this instead:

var lastTouch = null

window.addEventListener('touchstart', function (event) {
  lastTouch = event.touches[0]

window.addEventListener('touchend', function (event) {
  lastTouch = null

window.addEventListener('touchmove', function (event) {
  var currentTouch = event.changedTouches[0]
  if (lastTouch) {
  	target.scrollTop += currentTouch.clientY - lastTouch.clientY
  lastTouch = currentTouch

(To support multiple touch points you’d have to find the current touch by comparing it to the last touch’s identifier though.)

1 Like

Thank you sir, this was just amazing. Works perfectly fine.

1 Like