Slider slides many times

Reza Saadati

I am trying to create a slider with event listeners touchstart and touchmove.

The slider works very good, if you click on the buttons. But if you move your finger from left to right, it slides many times until the last image but it should only slide once. Also you cannot slide back.

var i = 0;

// Go next
$('.next').bind('click', function() {           
    niceSlider('left', '<');
});

// Go Back
$('.back').bind('click', function() {
    niceSlider('right', '>', 0); 
});

// Greather or less
function greatherOrLess(num1, operator, num2) {
    if (operator == '<') {
    return (num1 < num2) ? true : false;
  }
  else if (operator == '>') {
    return (num1 > num2) ? true : false;
  }
}

// Slider
function niceSlider(direction, operator, NumberOfAllImages = 4, position = 600) {
  var direction = (direction == 'left') ? '-' : '+';  
  if (greatherOrLess(i, operator, NumberOfAllImages)) {
    if (direction == '+' || direction == '-') {
      $('li').animate({'left': direction + '=600px'}, 300).delay(600);  
      x = (direction == '-') ? i++ : i--;
    }
  }
  console.log($('li:first').position().left);
  console.log(x);   
}

// Event Listener
var slider = document.querySelector('.slider');
slider.addEventListener('touchstart', handleTouchStart, false);
slider.addEventListener('touchmove', handleTouchMove, false);

// Start from touch
function handleTouchStart(evt) {
  startClientX = evt.touches[0].clientX;
  startClientY = evt.touches[0].clientY;
}

// Move from touch
function handleTouchMove(evt) {
  moveClientX = evt.touches[0].clientX;
  moveClientY = evt.touches[0].clientY;

  var diffClientX = startClientX - moveClientX;
  var diffClientY = startClientY - moveClientY;

  if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
    if (diffClientX > 0) {
      niceSlider('left', '<');
    }
    else {
      niceSlider('right', '>');
    }
  }
}

There must be something wrong with the function handleTouchMove. How can I fix it?

https://jsfiddle.net/6t1wx95f/16/

Durga
function handleTouchStart(evt) {
  startClientX = evt.touches[0].clientX;
  startClientY = evt.touches[0].clientY;
  checkTouch = true;
}

// Move from touch
function handleTouchMove(evt) {
  moveClientX = evt.touches[0].clientX;
  moveClientY = evt.touches[0].clientY;

  if (checkTouch) {
    var diffClientX = startClientX - moveClientX;
    var diffClientY = startClientY - moveClientY;
    if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
      if (diffClientX > 0) {
        niceSlider('left', '<');
      } else {
        niceSlider('right', '>', 0);
      }
    }
    checkTouch = false;
  }
}

function handleTouchEnd(evt) {
  checkTouch = true;
}

Here is jsFiddle, check it for only once use a boolean value. On touch move next function was calling on every move.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related