0

I have seen many similar questions, but surprisingly they are completely different.

I want a way for a user with a touch screen to be able to drag his finger over multiple elements over the page in one stroke, and as his finger moves from one element to another, have those elements fire events similar to if a mouse were moved over them. So each element would fire something equivalent to a touchenter and touchleave event or something.

JQuery mobile supports a number of touch events: touchstart, touchend, touchmove, touchcancel, tap, swipe, taphold but I cannot seem to use them to achieve it.

Say I have n elements, I have code like this:

        function applyDown(idx){ /*...*/ }
        function applyUp(idx){ /*...*/ }
        function go(idx, fn){
            return function(){
                fn(idx);
            }
        }
        for (var i = 0; i < n; i++){
            $(".element_"+i).on("touchstart", go(i, applyDown));
            $(".element_"+i).on("touchmove", go(i, applyDown));
            $(".element_"+i).on("touchend", go(i, applyUp));
        }

If I start touching one element and swipe to another element, then release, the second element never has applyDown() called on it, and the first element only has applyUp() called when the finger is released from the screen (whereas it should be called as soon as the finger leaves the element).

How can I achieve what I want?

I used touchmove above because I thought it would solve the problem, but the behaviour is identical with or without it.

These elements are actually complex SVG shapes, so I don't know if it will rule out some hacky(?) alternatives such as, for example, using javascript to calculate which element the finger is over at any point in time.

Community
  • 1
  • 1
CL22
  • 13,696
  • 23
  • 83
  • 147

1 Answers1

2

I ended up using the hacky solution: looking for the SVG element, given the position of the touch:

        $(document).on("touchmove touchstart", function(event){
            var x = event.originalEvent.touches[0].pageX;
            var y = event.originalEvent.touches[0].pageY;
            var e = document.elementFromPoint(x, y);
            // remove existing hover effects
            $(".element")
                    .attr("stroke-width", "1")
                    .attr("stroke", "#bbb")
                    .attr("fill", "#eee");
            // add hover effect to matching element
            $(e).filter(".element")
                    .attr("stroke-width", "2")
                    .attr("stroke", "#181")
                    .attr("fill", "#afa");
        });
        $(document).on("touchend", function(event){
            $(".element")
                    .attr("stroke-width", "1")
                    .attr("stroke", "#bbb")
                    .attr("fill", "#eee");
        });
CL22
  • 13,696
  • 23
  • 83
  • 147