Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element on touchstart?

I have a series of divs on a page which you can swipe left on, which will reveal a div underneath. This works fine when there is only one element, but when there are multiple, they all swipe in unison, instead of the one getting swiped alone.

To remedy this, I tried the ideas here: Find element finger is on during a touchend event

Problem is, now only the first element gets swiped, while the rest of them stay stationary. Any ideas on how I could fix this? I thought I could use this, but it would always return the window object.

Code:

var originalCoord = {
        x: 100,
        y: 100
    }
    var finalCoord = {
        x: 100,
        y: 100
    }

    function touchMove(event) {
        event.preventDefault();
        finalCoord.x = event.targetTouches[0].pageX
        finalCoord.y = event.targetTouches[0].pageY
    }

    function touchEnd(event) {
        var changeY = originalCoord.y - finalCoord.y
        if (changeY < 30 && changeY > (30 * -1)) {
            changeX = originalCoord.x - finalCoord.x
            if (changeX > 10) {
               var elem = document.elementFromPoint(event.pageX, event.pageY);
               console.log(elem);
                $(elem).css("margin-left", "-54px");
                setTimeout(function () {
                    $(elem).css("margin-left", "0px");}
                , 500);
            }
        }
    }

    function touchStart(event) {
        originalCoord.x = event.targetTouches[0].pageX
        originalCoord.y = event.targetTouches[0].pageY
        finalCoord.x = originalCoord.x
        finalCoord.y = originalCoord.y
    }

    this.addEventListener("touchstart", touchStart, false);
    this.addEventListener("touchmove", touchMove, false);
    this.addEventListener("touchend", touchEnd, false);

Demo (only works on iOS): http://www.codekraken.com/testing/snowday/swipe.html

like image 422
Charlie Avatar asked Mar 17 '26 01:03

Charlie


1 Answers

You can get the element which the event originated in by using event.target.

function touchStart(event){
  var currentElement = event.target;
}
like image 151
ahren Avatar answered Mar 18 '26 13:03

ahren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!