简体   繁体   中英

javascript - Swipe gesture not detecting

I have found code on another question on stack overflow and I used the same code but it does not work. I have tried it on iphone using safari and chrome and on an android device using chrome as well. Can't figure out why the event handler is not working.

The aim of the gestures is to change the background color using rgb values. the desktop version works and is up at andy.serra.us if you want to check. And now, I am trying to build the mobile version.

document.body.addEventListener('touchstart', handleTouchStart(event), false);
document.body.addEventListener('touchmove', handleTouchMove(event), false);

var xDown = null;
var yDown = null;

function handleTouchStart(event) {
  if(screen && screen.width < 480 && !(document.getElementsByClassName('in')[0])) {
    xDown = event.touches[0].clientX;
    yDown = event.touches[0].clientY;
  }
};

function handleTouchMove(event) {
  if(screen && screen.width < 480 && !(document.getElementsByClassName('in')[0])) {
    if ( ! xDown || ! yDown ) {
        return;
    }
    var xUp = event.touches[0].clientX;
    var yUp = event.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
          red -= increment;
          if(red < 0) { red = 0; }
          document.getElementById("val-display").innerHTML = "Red: " + red + "<br>Green: " + green + "<br>Blue: " + blue + "<br>Hex: #" + fullColorHex(red, green, blue);
        } else {
          blue -= increment;
          if(blue < 0) { blue = 0; }
          document.getElementById("val-display").innerHTML = "Red: " + red + "<br>Green: " + green + "<br>Blue: " + blue + "<br>Hex: #" + fullColorHex(red, green, blue);
        }
    } else {
        if ( yDiff > 0 ) {
          green -= increment;
          if(green < 0) { green = 0; }
          document.getElementById("val-display").innerHTML = "Red: " + red + "<br>Green: " + green + "<br>Blue: " + blue + "<br>Hex: #" + fullColorHex(red, green, blue);
        }
    }
    setBackgroundColor();
    setTextColorFromBackground("title", false);
    setTextColorFromBackground("side_box", true);
      /* reset values */
    xDown = null;
    yDown = null;
  }
};

If what you want is a cross platform swipe listener i just kind of uploaded one on npm. It is called goodtap and handles tap, swipe, longpress and outside tap and requires no individual eventlisteners so any generated html will automatically work.

GoodTap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM