0

I have a JS code that adds event listeners for mouse action. I would like to add the same for touch to support mobile devices. I've attempted to do something like this:

var i = 0;
                            
let loc = document.querySelectorAll("a[data-lat]");

loc.forEach(function(node) {
    node.addEventListener("mouseenter", locOver); // old working code
    node.addEventListener("touchstart", locOver); // added for touch support
    node.addEventListener("mouseleave", locOut);  // old working code
    node.addEventListener("touchend", locOut);    // added for touch support
    node.id = i++;
});

Unfortunately nothing happens. I guess this would be too easy, hah? I'm trying to do it in plain vanila JS.

santa
  • 12,234
  • 49
  • 155
  • 255
  • 1
    Read this: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events – Randy Casburn Feb 15 '21 at 02:07
  • Are you trying to run a function when the user is swiping or something else? I ask just because mouseenter/mouseleave is more of a hover thing, and touchstart/touchend is more of a click and drag thing. So not exactly the same thing, but maybe that's good for your purposes? – cjl750 Feb 15 '21 at 03:23
  • @cjl750 Yes, I am thinking of changing my functionality, On a desktop it is a list and when someone hovers overs it shows on the map relative to your current location, but on a phone most of the list items are below the fold... Also it works great to hover over and click on a desktop but on a mobile it's a bit confusing, frequently acts as a click. – santa Feb 15 '21 at 14:24
  • I see. In that case it may just make more sense to basically just have the users click on mobile, in which case probably nothing would need to be done to your code. (Sounds like you already have a click listener on desktop, which will still work on mobile.) But if you decide you want something different and can update the question, I'd be happy to take a look. Meanwhile, I'll leave you with this golden question that I've referred to often about swipe support in JS: https://stackoverflow.com/questions/2264072/detect-a-finger-swipe-through-javascript-on-the-iphone-and-android – cjl750 Feb 15 '21 at 20:21

0 Answers0