1

I'm trying to get around the way iOS handles javascript and scrolling with a js function I'm calling through window.onscroll. The problem is that in iOS, the javascript is not called until after scrolling has stopped. To work around this, I was hoping to add an event listener that prevents the default behavior, calls my function, then dispatches the original touch event. Something like this:

// Helper function to clone event
function clone_obj(obj) {
    if(obj == null || typeof(obj) !== 'object') {
      return obj;
    }
    var temp = document.createEvent("TouchEvent");
    for (var key in obj) {
      temp[key] = obj[key];
    }
    return temp;
  }

document.body.addEventListener("touchstart", function(event) {
    event.preventDefault();
    // clone the event using helper function
    var clonedEvent = clone_obj(event);
    // run my javascript function
    animateNav();
    // initialize and dispatch clonedEvent
    clonedEvent.initTouchEvent();
    event.target.dispatchEvent(clonedEvent);
  });

The clone_obj helper function is derived from an SO post, but it doesn't seem to provide a deep clone. If I try to clone using $.extend or event.constructor, I get TypeError: Illegal constructor.

Anyone know of another workaround, or if it's possible to clone a touch event?

As a side note, I tried the HammerJS library to call my function on swipe and drag events, but it still wasn't calling my function until after scrolling stopped.

Community
  • 1
  • 1
nkanderson
  • 483
  • 1
  • 8
  • 21

1 Answers1

0

This is intended behavior by iOS and other mobile operating systems. Since this is not a bug, it is not wise to circumvent this limitation; hacking around such limitations can cause inconsistent and buggy results across devices.

If you would like scroll events to occur on mobile, the best approach is to use a custom scollbar system. From the browser perspective, the webpage is never scrolling, rather the contents of the webpage are scrolling within the body. iScroll (https://github.com/cubiq/iscroll) is a popular library to create custom scrolling. It depends on the circumstance, but custom scrolling should be used sparingly and carefully. Remember, you are completely circumventing the native scrolling; native scrollers know more about the user, their preferences, and the device than you could know.

NickHTTPS
  • 744
  • 4
  • 16
Jason
  • 4,079
  • 4
  • 22
  • 32