Crossing over to new elements during touchmove

spike picture spike · Sep 12, 2012 · Viewed 11.6k times · Source

I'd like to make it so that as you drag your finger over a set of elements, the background of the one you've got your finger on changes.

It seems like I want to use the touchmove event for this, but as far as I can tell the target element never changes, even as you drag around. The clientX and clientY do change, and I found this document.elementFromPoint function that works in chrome, but seems very roundabout (plus I'm not sure which browsers support it)

See this fiddle, I want the boxes to turn green as you touch through them:

http://jsfiddle.net/QcQYa/9/

By the way, in chrome, you'll need to go into the user agent tab of the inspector config modal and choose "emulate touch events" to see my example.

Edit: I found an idea to use mouseenter here How to detect html elements on touchmove and got it to work on desktop chrome, but not on mobile safari.

Answer

dan-lee picture dan-lee · Sep 13, 2012

I took a different approach:

Every touch event I check if the touch position is inside a $('.catch') object.

function highlightHoveredObject(x, y) {
    $('.catch').each(function() {
      // check if is inside boundaries
      if (!(
          x <= $(this).offset().left || x >= $(this).offset().left + $(this).outerWidth() ||
          y <= $(this).offset().top  || y >= $(this).offset().top + $(this).outerHeight()
      )) {

        $('.catch').removeClass('green');
        $(this).addClass('green');
      }
    });
}

You can see it working on jsFiddle.
It works on Chrome, I hope it also does on mobile devices.

Edit:
In this fiddle I used both versions, mine and that one from the link in the comments (document.elementFromPoint – a jQuery solution), both seem to work on my Android phone. I also added a quick and dirty benchmark (see console) and as expected document.elementFromPoint is a few thousandth faster, if that is your concern you should check the support of document.elementFromPoint for the browsers you want to support.