Move chess pieces with translate3d that snaps to center of div using CSS JavaScript

  css, html, javascript

I created a chess app and I’m using touch events so that the pieces can be dragged by touch. I want the users to see the piece being dragged. To accomplish this I’m using translate3d to move the piece across the screen. How can I get the pieces to snap to center of the square?

Here’s the code I’m using to drag the pieces:

function drag(e) {
  e.preventDefault()

  if (e.type === 'touchmove') {
    currentX = e.touches[0].clientX - initialX
    currentY = e.touches[0].clientY - initialY
  } else {
    currentX = e.clientX - initialX
    currentY = e.clientY - initialY
  }

  xOffset = currentX
  yOffset = currentY

  e.target.style.transform = 'translate3d(' + currentX + 'px, ' + currentY + 'px, 0)'
  }
}

Source: Ask Javascript Questions

LEAVE A COMMENT