Javascript touch movement, track when user swipes from edges

后端 未结 3 1482
礼貌的吻别
礼貌的吻别 2020-12-16 22:37

I need to track user touch events. I want to track when user swipes from edges.
For example when user swipes from left vertical edge I will show a menu, from right edge

相关标签:
3条回答
  • 2020-12-16 22:53

    I think this will work:

    first check if the touchstart event happens at the edge of the screen:

    var startDragAtBorder = false;
    $(document).on('touchstart', function(e) {
       var xPos = e.originalEvent.touches[0].pageX;
    
       if(xPos < 5) { // this can also be xPos == 0; whatever works for you
        startDragAtBorder = true;   
       }
       else{
        startDragAtBorder = false;
       }
    });
    

    than setup the drag event with Hammer:

    $(document).hammer().on('drag', function(e){
      if(startDragAtBorder && e.gesture.direction == 'right'){
        // check that the drag event started at the edge and that the direction is to the right
    
        var currentText = $('#logArea').text();   
        $('#logArea').text(""+currentText+" . "+e.type);
      }
    });
    

    working fiddle: http://jsfiddle.net/ym4JV/55/

    0 讨论(0)
  • 2020-12-16 22:59

    I had trouble making this work using Hammer.JS - v2.0.8 and refering to the actual documentation.
    Based on 2BitNerd's answer here is what I used:

    Hammer(document.body).on("swiperight", function(e) {
        var endPoint = e.pointers[0].pageX;
        var distance = e.distance;
        var origin = endPoint - distance;
        if (origin <= 15) {
            // They swiped, starting from no more than 15px away from the edge. 
        }
    });
    

    The .gesture attribute has to be skipped for me to make this work as it does not exist.

    0 讨论(0)
  • 2020-12-16 23:09

    Using Hammer.js v2.0.4, I found that this worked best:

    $("html").hammer().on('swiperight', function (e) {
        var endPoint = e.pointers[0].pageX;
        var distance = e.distance;
        var origin = endPoint - distance;
    
        if (origin <= 15) {
            // They swiped, starting from no more than 15px away from the edge. 
        }
    });
    
    0 讨论(0)
提交回复
热议问题