Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hammer.js and preventDefault();

js to also support touch-gestures. I'm bagging my head about prevent default actions. when I set event.preventDefault or event.gesture.preventDefault() or even apply parameter {prevent_defaults: true } on hammer it just triggers default action on the anchor. How can I prevent that and/or what am I doing wrong?!

Code snippet;

function initializeNavigation() {
    $("nav").hammer({prevent_defaults: true }).on("tap", "a", function(event) {
        event.preventDefault();
        event.gesture.preventDefault();
        var target = $(this.hash);
        scrollToTarget(target, 1200);
        // if there is an open detailItem then close it.
        if (detailItemOpen) {
            $("div." + detailItemOpen).slideUp();
        }
    })

    if (Modernizr.mq('only screen and (max-width: 767px)'))  {
        initializeMobileMenuAndSetButton();
    }
}
like image 521
myradon Avatar asked Nov 11 '22 23:11

myradon


1 Answers

Considering Hammer 2.0+ event.gesture is no longer and Event, but a simple Object.

event.gesture.srcEvent will not be the proper event to stopPropagation on, so it will not work.

If you are using the tap event, and want to prevent click/taps on the document you can do something like this. We need to create a global tap handler that will replace the original methods stopPropagation and preventDefault

function createHandler(event) {
  return {
    isHandled: false,
    _shouldStopPropagation: false,
    _shoulePreventDefault: false,
    stopPropagation: event.stopPropagation.bind(event),
    preventDefault: event.preventDefault.bind(event),
  }
}


function handleEvent(handler, node) {
  let clickHandler; 


  if (!handler.isHandled) {
    handler.isHandled = true;
    document.addEventListener('click', clickHandler = (event)=> {
      if (handler._shouldStopPropagation) {
        handler.stopPropagation();
        event.stopPropagation();
      }
      
      if (handler._shoulePreventDefault) {
        handler.preventDefault();
        event.preventDefault();
      }
      document.removeEventListener('click', clickHandler, true);
    }, true);
  }
}


// Create a global tap Event so we can replace the original functions
document.addEventListener('tap', (event)=> {
  let handler = createHandler(event);

  event.stopPropagation = function() {
    handler._shouldStopPropagation = true;
    handleEvent(handler);
  };
  event.preventDefault  = function() {
    handler._shoulePreventDefault = true;
    handleEvent(handler);
  }
}, true);

// Now we can use it.
document.addEventListener('tap', (event)=> {
  /* If you want to prevent Default */
  event.preventDefault();

  /* If you want to stop propagation */
  event.stopPropagation();

  /* If you want to do both */
  event.preventDefault();
  event.stopPropagation();
});
like image 131
Joel Cox Avatar answered Nov 15 '22 00:11

Joel Cox