technopeasant
technopeasant

Reputation: 7949

javascript touchend if element is over another

Confused on the best method to measure if an element is over another element (visually) during a touchend event. Essentially I'm implementing a touch-friendly drag and drop.

I've seen a little bit on .elementFromPoint() and event.touches, but am unsure how to use these to measure a specific element's bounds. Something like the below.

.bind('touchend', function(e){

    e.preventDefault();

    /* IF (targ is within titles bounds) { append targ to titles} */
    if (titles == document.elementFromPoint(orig.touches[0].pageX,orig.touches[0].pageY)){

        titles.append(targ);
    }

    targ.removeClass('moving').removeAttr('style');
});

Upvotes: 2

Views: 961

Answers (1)

ericjam
ericjam

Reputation: 1519

This seems to work seamlessly for me, constantly toggle zindex on the dragged element so you can obtain the element below.

element.addEventListener('touchmove', touchMove, false);

function touchMove(event) {
    var x = event.targetTouches[0].clientX;
    var y = event.targetTouches[0].clientY;
    dragger.style.zIndex = -1;
    var hoveredElement = document.elementFromPoint(x, y);
    console.log(hoveredElement);
    dragger.style.zIndex = options.draggerZIndex;

}

If you can ignore old browsers this answer javascript - elementFromPoint select bottom element works too just add pointer-events: none

Upvotes: 0

Related Questions