Search code examples
javascriptreactjstouch

Get elements in the path of a touch event


I have a grid of squares. I want the user to be able to touch and move across the grid, and each square to change colour when the touch goes over it.

I've looked at onTouchStart, onTouchMove and onTouchEnd. Using onTouchMove, the event.target is always the element where the touch began.

How can I find the elements that are moved over with the touch?

JSFiddle


Solution

  • I managed to solve this as follows;

    Added onTouchMove onto the wrapping element

    <div onTouchMove={this.onTouch}>

    Handle that touchMove event by calculating the child position

    onTouch: function(e) {
      const coords={
        x: parseInt(e.touches[0].pageX/boxSize, 10),
        y: parseInt(e.touches[0].pageY/boxSize, 10)
      }
      this.handleChildChange(coords.x, coords.y);
    }
    

    This calculates the coordinates of the box and triggers the colour change

    handleChildChange: function(x, y) {
      this.props.grid[y][x].c=1;
      this.forceUpdate()
    }
    

    Box onMouseEnter for mouse handling

    onMouseEnter={this.props.handleChange.bind(this, this.props.box.x, this.props.box.y)}
    

    On each box item, I keep the onMouseEnter so that both touch and mouse move are handled in the same way

    JSFiddle