Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. // Adapted from an article by Ryan Fioravanti and Angular Hammer code by Ryan S Mullins.
  2. function preventGhosts (element) {
  3. let coordinates = []
  4. const threshold = 25
  5. const timeout = 2500
  6.  
  7. if ('ontouchstart' in window) {
  8. element.addEventListener('touchstart', resetCoordinates, true)
  9. element.addEventListener('touchend', registerCoordinates, true)
  10.  
  11. window.document.addEventListener('click', preventGhostClick, true)
  12. }
  13.  
  14. /**
  15. * prevent clicks if they're in a registered XY region
  16. * @param {MouseEvent} ev
  17. */
  18. function preventGhostClick (ev) {
  19. for (var i = 0; i < coordinates.length; i++) {
  20. var x = coordinates[i][0]
  21. var y = coordinates[i][1]
  22.  
  23. // within the range, so prevent the click
  24. if (Math.abs(ev.clientX - x) < threshold &&
  25. Math.abs(ev.clientY - y) < threshold) {
  26. ev.stopPropagation()
  27. ev.preventDefault()
  28. break
  29. }
  30. }
  31. }
  32.  
  33. /**
  34. * reset the coordinates array
  35. */
  36. function resetCoordinates () {
  37. coordinates = []
  38. }
  39.  
  40. /**
  41. * remove the first coordinates set from the array
  42. */
  43. function popCoordinates () {
  44. coordinates.splice(0, 1)
  45. }
  46.  
  47. /**
  48. * if it is an final touchend, we want to register it's place
  49. * @param {TouchEvent} ev
  50. */
  51. function registerCoordinates (ev) {
  52. // touchend is triggered on every releasing finger
  53. // changed touches always contain the removed touches on a touchend
  54. // the touches object might contain these also at some browsers (firefox os)
  55. // so touches - changedTouches will be 0 or lower, like -1, on the final touchend
  56. if (ev.touches.length - ev.changedTouches.length <= 0) {
  57. var touch = ev.changedTouches[0]
  58. coordinates.push([touch.clientX, touch.clientY])
  59.  
  60. setTimeout(popCoordinates, timeout)
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement