1

I want to make it so swiping over an image will take a user to the previous or next image, depending on the direction of the swipe. That part works great, BUT it removes the ability to zoom in on the image. According to this answer the solution is to enable touchAction: 'auto', but that breaks hammer.js entirely, preventing it from working for swipe at all.

Code:

<script src="../js/hammer.min.js"></script>
<script>
$('.imagecontainer').each(function(){
  var options = {
    touchAction: 'auto',
  };
  var mc = new Hammer(this, options);

  mc.on("swipeleft", function() {
    navTo('jsnavnext');
    return false;
  });
  mc.on("swiperight", function() {
    navTo('jsnavprev');
    return false;
  });
});
</script>

I can get pinch-zoom to work in the least user-friendly way possible with touchAction: 'pan-y' (basically requires the user to make a wacky circle motion), but that's not...great. Ideally I'd like hammer.js to ONLY add swipe navigation and not touch any other default behaviour.

1 Answer 1

0

I had a problem that was similar. I wanted to be able to detect swipes on a div and also be able to pinch zoom on the div. The swipe listener alone seemed to disable zoom. Adding touchAction:'auto' allowed me to pinch zoom, but it read would both fire my swipe action and scroll (I didn't want it to scroll, just wanted to fire the swipe action). The key part of the solution I have here is using recognizeWith, and then call preventDefault on panstart and panmove. This leaves me with just the desired pinch zoom and swipes

Here's my solution:

  var target = document.getElementById("target-div")
  var mc = new Hammer(target, {touchAction: 'auto' });

  mc.add( new Hammer.Pan({
    direction: Hammer.DIRECTION_ALL,
    threshold: 0 }) );

  mc.add(new Hammer.Swipe({
    direction: Hammer.DIRECTION_ALL,
    threshold: 1,
    velocity:0.1
  })).recognizeWith(mc.get('pan'));

  mc.on('panstart panmove', function(ev) { ev.preventDefault(); });

  mc.get('pinch').set({ enable: true });

  mc.on("pinch", function(ev) {
  //do anything you need to here, or not 
  });

  mc.on("swipeleft", function(ev) {
  //do something
  }

  mc.on("swiperight", function(ev) {
  //do something
  }

I am still new to hammer.js, but I have noticed a lot of issues on github where people are trying to combine multiple gestures on the same element. I hope this helps!

1
  • 1
    I'm trying to pan without disabling pinch zoom, but even with the added preventDefault for panning I still get my pans prematurely terminated.
    – Michael
    Commented Feb 18, 2018 at 2:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.