)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Local Mouse Click

  1. const RIGHT_BOUND = 200;
  2. const measureEl = document.createElement('div');
  3.  
  4. Object.assign(measureEl.style, {
  5.   position: 'absolute',
  6.   left: 0,
  7.   top: 0,
  8.   zIndex: 999
  9. });
  10.  
  11. function localPosition(e, element, w = 1, h = 1) {
  12.  
  13.   // normalize desktop and mobile
  14.   const touches = e.touches;
  15.   let x;
  16.   let y;
  17.   if (touches != null && touches.length > 0) {
  18.     x = touches[0].clientX;
  19.     y = touches[0].clientY;
  20.   } else {
  21.     x = e.clientX;
  22.     y = e.clientY;
  23.   }
  24.  
  25.   function location(width) {
  26.     let left = 0;
  27.     let right = RIGHT_BOUND;
  28.     let mid;
  29.  
  30.     while (right - left > 0.0001) {
  31.       mid = (right + left) / 2;
  32.  
  33.       measureEl.style[width ? 'width' : 'height'] = `${mid}%`;
  34.       measureEl.style[width ? 'height' : 'width'] = '100%';
  35.       element.appendChild(measureEl);
  36.       const el = document.elementFromPoint(x, y);
  37.  
  38.       element.removeChild(measureEl);
  39.       if (el === measureEl) {
  40.         right = mid;
  41.       } else {
  42.         if (right === RIGHT_BOUND) {
  43.           return null;
  44.         }
  45.         left = mid;
  46.       }
  47.     }
  48.  
  49.     return mid;
  50.   }
  51.  
  52.   const left = location(1);
  53.   const top = location(0);
  54.   return left != null && top != null
  55.     ? {
  56.         // percentage values
  57.         left,
  58.         top,
  59.         // pixel values
  60.         x: left * w * 0.01,
  61.         y: top * h * 0.01
  62.       }
  63.     : null;
  64. }
  65.  
  66. const div = document.body.appendChild(document.createElement('div'));
  67. div.innerHTML = 'click me';
  68. Object.assign(div.style, {
  69.   postition: 'absolute',
  70.   transform: 'translate(20px, 20px) rotate(45deg) scale(0.8)',
  71.   width: '120px',
  72.   height: '90px',
  73.   color: 'white',
  74.   fontFamily: 'sans-serif',
  75.   background: 'gray'
  76. });
  77.  
  78. document.addEventListener('touchstart', onClick);
  79. document.addEventListener('mousedown', onClick);
  80.  
  81. function onClick(e) {
  82.   const info = localPosition(e, e.target, 120, 90);
  83.   console.log(info);
  84. }

Find the local percentage and pixel values of the mouse/touch location.

I found this one on stackoverflow here by user 4esn0k.

This is an interesting alternative to semi-broken native browser solutions and custom matrix math 😉

// css // dom // html // javascript // math
snippet.zone ~ 2021-24 /// {s/z}